aycanadal
aycanadal

Reputation: 1146

Returning DTO from @RestControllerAdvice @ExceptionHandler method

I have the following @ExceptionHandler method in a @RestControllerAdvice:

 @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);

}

And the ErrorDto is:

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;

    }

}

But the response I get when a BusinessException is thrown is:

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

Why don't I see the ErrorDto in the response?

Upvotes: 1

Views: 1712

Answers (1)

aycanadal
aycanadal

Reputation: 1146

ErrorDto fields needed to be public or need to have public getters.

Upvotes: 1

Related Questions