javaspringrestexceptioncontroller-advice

Customize Global Exception Handler in java Spring Boot


My GlobalExceptionHandler

@ControllerAdvice("uz.pdp.warehouse")
public class GlobalExceptionHandler {

    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<DataDto<AppError>> handle500(RuntimeException e, WebRequest webRequest) {
        return new ResponseEntity<>(
                new DataDto<>(AppErrorDto.builder()
                        .message(e.getMessage())
                        .status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .path(webRequest.getContextPath())
                        .build()));
    }

}

I want to return my customized ResponseEntity but it returns something different

{
"timestamp": "2022-03-27T06:21:00.845+00:00",`
"status": 404,
"error": "Not Found",
"trace": "uz.pdp.warehouse.exception.NotFoundException: QWE\r\n",
"message": "QWE",
"path": "/test/testN"
}

then I also catch exception with try{}catch(){} it is working but I want to handle exception via my GlobalExceptionHandler.

Is it possible return customized AppError or ResponseEntity?


Solution

  • You would need to extend ResponseEntityExceptionHandler as follows:

    @ControllerAdvice("uz.pdp.warehouse")
    public class GlobalExceptionHandler extends ResponseEntityExceptionHandler  {
    
        @ExceptionHandler({RuntimeException.class})
        public ResponseEntity<DataDto<AppError>> handle500(RuntimeException e, WebRequest webRequest) {
            return new ResponseEntity<>(
                    new DataDto<>(AppErrorDto.builder()
                            .message(e.getMessage())
                            .status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .path(webRequest.getContextPath())
                            .build()));
        }
    
    }