【问题标题】:Spring boot @ExceptionHandler not responding with custom responseSpring boot @ExceptionHandler 没有响应自定义响应
【发布时间】:2021-01-28 07:18:11
【问题描述】:

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

预期响应

{
    "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
}

【问题讨论】:

标签: java spring spring-boot exception java-8


【解决方案1】:
@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {

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

    }
}

试试这个

【讨论】:

  • @Akshay Patil 我看到代码现在按预期工作
猜你喜欢
  • 2018-11-07
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 2021-02-24
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多