【问题标题】:Returning DTO from @RestControllerAdvice @ExceptionHandler method从@RestControllerAdvice @ExceptionHandler 方法返回 DTO
【发布时间】:2017-12-24 13:30:13
【问题描述】:

我在@RestControllerAdvice 中有以下@ExceptionHandler 方法:

 @ExceptionHandler(BusinessException.class)
 public ResponseEntity<Object> onException(BusinessException exception, WebRequest request) {

     Locale locale = request.getLocale();
     String message = messageSource.getMessage(exception.errorCode.toString(),
             exception.arguments, locale);

     ErrorDto errorDto = new ErrorDto(
             exception.errorCode,
             exception.arguments,
             message
     );

     return new ResponseEntity(errorDto, new HttpHeaders(), HttpStatus.CONFLICT);

}

ErrorDto 是:

public class ErrorDto {

    ErrorCode errorCode;
    String[] arguments = new String[]{};
    String message;

    public ErrorDto(ErrorCode errorCode, String[] arguments, String message){

        this.errorCode = errorCode;
        this.arguments = arguments;
        this.message = message;

    }

}

但是当BusinessException 被抛出时我得到的响应是:

{
    "timestamp": 1500459833663,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.ciet.app.exceptions.BusinessException",
    "message": "No message available",
    "path": "/CietApi/errorCodeTest"
}

为什么我在回复中看不到ErrorDto

【问题讨论】:

  • 您确定在异常发生时调用了给定的 ExceptionHandler。根据响应,它由默认的 ExceptionHandler 处理。
  • 移除 WebRequest 请求参数。然后尝试。
  • 是的,我可以调试并查看处理程序内部的 return 语句被调用。此外,如果我返回异常本身而不是 DTO,我会得到异常作为响应。删除 WebRequest 参数也无济于事。无论如何,我需要它来获取语言环境。
  • 检查是否有其他@ControllerAdive
  • 我没有。问题是 dto 字段不是公开的。有趣的是,默认处理程序会在没有警告的情况下处理异常。

标签: spring spring-boot


【解决方案1】:

ErrorDto 字段需要公开或需要有公开的 getter。

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    相关资源
    最近更新 更多