我有一个带有@restcontrolleradvice和@exceptionhandler(apiexception.class)方法的全局异常处理程序。我已经设计了自己的响应类validationresponse.class,并将其添加到响应实体类中。我想用validationresponse来响应,但是得到一些通用的响应。
全局异常处理程序
@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());
}
}
自定义异常类
@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;
}
}
自定义响应设计
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(Include.NON_NULL)
public class ValidationResponse {
public int errorCode;
public String errorMessage;
}
预期React
{
"errorCode": 1010,
"errorMessage": "some custome validation message"
}
电流响应
{
"error-message" : "Request processing failed; nested exception is com.package.exception.APIException",
"error-code" : "GENERAL_ERROR",
"trace-id" : null,
"span-id" : null
}
1条答案
按热度按时间hts6caw31#
试试这个