[英]Spring boot @ExceptionHandler not responding with custom response
I have a global exception handler with @RestControllerAdvice and @ExceptionHandler(APIException.class) methods.我有一个带有 @RestControllerAdvice 和 @ExceptionHandler(APIException.class) 方法的全局异常处理程序。 I have designed my own response class ValidationResponse.class which I am adding to Response entity class.我设计了自己的响应 class ValidationResponse.class,我将其添加到响应实体 class。 I want to respond with ValidationResponse but getting some generic response instead.我想用 ValidationResponse 回应,但得到一些通用的回应。
Global Exception Handler全局异常处理程序
@RestControllerAdvice
public class RestResponseExceptionHandler {
@ExceptionHandler(APIException.class)
public ResponseEntity<ValidationResponse> handleException(APIException ex) {
ValidationResponse validationResponse = new ValidationResponse(ex.getErrorCode(), ex.getErrorMessage());
return new ResponseEntity<>(validationResponse, ex.getHttpStatus());
}
}
Custom exception class自定义异常 class
@Getter
@Setter
public class APIException extends RuntimeException {
private int errorCode;
private String errorMessage;
private HttpStatus httpStatus;
public APIException(int errorCode, String errorMessage, HttpStatus httpStatus) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.httpStatus = httpStatus;
}
public APIException(int errorCode, String errorMessage, HttpStatus httpStatus, Exception e) {
super(e);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.httpStatus = httpStatus;
}
}
Custom response design自定义响应设计
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(Include.NON_NULL)
public class ValidationResponse {
public int errorCode;
public String errorMessage;
}
Expected response预期响应
{
"errorCode": 1010,
"errorMessage": "some custome validation message"
}
Current Response当前响应
{
"error-message" : "Request processing failed; nested exception is com.package.exception.APIException",
"error-code" : "GENERAL_ERROR",
"trace-id" : null,
"span-id" : null
}
@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(APIException.class)
public ResponseEntity<ValidationResponse> handleException(APIException ex, WebRequest webRequest) {
}
}
Try this尝试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.