猿问

如何在自定义异常构造函数参数中使用多个错误特定参数?

我正在构建一个类似这样的自定义异常。


public class ValidationException extends RuntimeException {


    public validationException(String errorId, String errorMsg) {

        super(errorId, errorMsg);

    }

}

这当然会引发错误,因为RuntimeException没有任何这样的构造函数来处理它。


我还想通过以下方式在GlobalExceptionalHandler中获取 errorId 和 errorMsg


ex.getMessage();


但我希望函数分别获取 errorId 和 errorMessage 。如何实现?


斯蒂芬大帝
浏览 99回答 1
1回答

海绵宝宝撒

您希望errorIdanderrorMsg作为 ValidationException 类的字段,就像您对普通类所做的那样。public class ValidationException extends RuntimeException {&nbsp; &nbsp; private String errorId;&nbsp; &nbsp; private String errorMsg;&nbsp; &nbsp; public validationException(String errorId, String errorMsg) {&nbsp; &nbsp; &nbsp; &nbsp; this.errorId = errorId;&nbsp; &nbsp; &nbsp; &nbsp; this.errorMsg = errorMsg;&nbsp; &nbsp; }&nbsp; &nbsp; public String getErrorId() {&nbsp; &nbsp; &nbsp; &nbsp; return this.errorId;&nbsp; &nbsp; }&nbsp; &nbsp; public String getErrorMsg() {&nbsp; &nbsp; &nbsp; &nbsp; return this.errorMsg;&nbsp; &nbsp; }}在您的 GlobalExceptionHandler 中:&nbsp; &nbsp; @ExceptionHandler(ValidationException.class)&nbsp; &nbsp; public ResponseEntity<SomeObject> handleValidationException(ValidationException ex) {&nbsp; &nbsp; &nbsp; &nbsp; // here you can do whatever you like&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ex.getErrorId();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ex.getErrorMsg();&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答