How can I send a custom problem for all internal errors with problem-spring-web?

183 Views Asked by At

When using zalando's problem-spring-web library, how can I make sure any internal server error does not send the details to the frontend? For example, instead of

"title": "Internal Server Error",
  "status": 500,
  "detail": "For input string: \"string\"; nested exception is java.lang.NumberFormatException: For input string: \"string\""
}

I want to send

"title": "Internal Server Error",
  "status": 500,
  "detail": "An unexpected error occurred."
}
1

There are 1 best solutions below

0
olgunyldz On

You can add add any exception type in your controller advice, ever your custom exception types. If you can add status and detail in your custom exception type, you can set the error response information.

public class ErrorResponse{
  private String status;
  private String detail;
}

@ControllerAdvice
public class ExceptionController {

 
    @ExceptionHandler(Throwable.class)
    private ResponseEntity<ErrorResponse> throwable() {
        ErrorResponse errorResponse = new ErrorResponse();//create error response depends of your needs
        return ResponseEntity.status(HttpStatus.OK)
        .body( errorResponse);
    }

    @ExceptionHandler(Exception.class)
    private ResponseEntity<ErrorResponse> exception() {
        ErrorResponse errorResponse = new ErrorResponse();//create error response depends of your needs
        return ResponseEntity.status(HttpStatus.OK)
        .body( errorResponse);
    }
}