2017-07-19 44 views
1

我有一个@RestControllerAdvice以下@ExceptionHandler方法:从@RestControllerAdvice @ExceptionHandler方法返回DTO

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

W嗨,我没有看到ErrorDto的回应?

+0

您确定在发生异常时调用给定的ExceptionHandler。根据响应,它由defult ExceptionHandler处理。 –

+0

删除WebRequest请求参数。然后尝试。 –

+0

是的,我可以调试,看到处理程序内部的返回语句被调用。此外,如果我返回异常本身而不是DTO,我会得到异常作为响应。删除WebRequest参数也没有帮助。无论如何,我需要它来获取语言环境。 – aycanadal

回答

1

ErrorDto需要公开领域或需要有公共获得者。