spring boot@exceptionhandler未响应自定义响应

ufj5ltwl  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(432)

我有一个带有@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
}
hts6caw3

hts6caw31#

@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(APIException.class)
    public ResponseEntity<ValidationResponse> handleException(APIException ex, WebRequest webRequest) {

    }
}

试试这个

相关问题