从@RestControllerAdvice @ExceptionHandler 方法返回 DTO

Posted

技术标签:

【中文标题】从@RestControllerAdvice @ExceptionHandler 方法返回 DTO【英文标题】:Returning DTO from @RestControllerAdvice @ExceptionHandler method 【发布时间】: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 字段不是公开的。有趣的是,默认处理程序会在没有警告的情况下处理异常。 【参考方案1】:

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

【讨论】:

以上是关于从@RestControllerAdvice @ExceptionHandler 方法返回 DTO的主要内容,如果未能解决你的问题,请参考以下文章

@RestControllerAdvice 未实例化

RestControllerAdvice,ControllerAdvice

@RestControllerAdvice注解 @ExceptionHandler注解

Spring:激活外部 RestControllerAdvice

@RestControllerAdvice 中许多项目的 basePacakage

Spring注解之@RestControllerAdvice