I have a Spring ControllerAdvice using Zalando Problem dependency. On making an http request using Postman, I can see the breakpoint enter the if condition below, but the http response returned is always a 404. What can I do to make it return an http 400 bad request response like the Problem object built below.
@Slf4j
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(ExceptionClassA.class)
public Problem exceptionClassA(final ExceptionClassA e) {
log.error(e.getMessage());
if (ObjectUtils.isNotEmpty(e.getCause()) && e.getCause() instanceof ExceptionClassB) {
return Problem.builder()
.withTitle("Error A")
.withDetail(e.getCause().getMessage())
.withStatus(Status.BAD_REQUEST)
.build();
}
return Problem.builder()
.withTitle("Error B")
.withDetail(e.getMessage())
.withStatus(Status.INTERNAL_SERVER_ERROR)
.build();
}
}
CodePudding user response:
Changing the return type and wrapping the problem inside a ResponseEntity fixed the issue. Here is the full code -
@Slf4j
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(ExceptionClassA.class)
public ResponseEntity<Problem> exceptionClassA(final ExceptionClassA e) {
log.error(e.getMessage());
if (ObjectUtils.isNotEmpty(e.getCause()) && e.getCause() instanceof ExceptionClassB) {
return ResponseEntity.badRequest()
.body(Problem.builder()
.withTitle("Error A")
.withDetail(e.getCause().getMessage())
.withStatus(Status.BAD_REQUEST)
.build());
}
return ResponseEntity.internalServerError()
.body(Problem.builder()
.withTitle("Error B")
.withDetail(e.getMessage())
.withStatus(Status.INTERNAL_SERVER_ERROR)
.build());
}
}