Hi, I'm trying to add an exception handler for ResponseStatusException in my Spring 3 project.
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@Autowired
private ObjectMapper objectMapper;
@ExceptionHandler({ResponseStatusException.class})
public ResponseEntity<Object> handle(ResponseStatusException e) {
ObjectNode node = objectMapper.createObjectNode()
.put("code", e.getStatusCode().value())
.put("details", e.getMessage());
return ResponseEntity.status(e.getStatusCode().value())
.contentType(MediaType.APPLICATION_JSON)
.body(node);
}
}
But, the handler doesn't get called when I throw an exception like this:
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No id has been provided!");
This approach works for other custom exceptions I have. But, it doesn't seem to trigger when using ResponseStatusException. I'm not sure why?
Here is my pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.1.0</version>
<exclusions>
<exclusion>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>3.1.0</version>
</dependency>
Comment From: wilkinsona
I can't reproduce the behavior that you have described using Spring Boot 3.1.0 or 3.1.2 (the latest 3.1.x release). The response is as expected:
HTTP/1.1 400
Connection: close
Content-Type: application/json
Date: Mon, 24 Jul 2023 10:25:49 GMT
Transfer-Encoding: chunked
{
"code": 400,
"details": "400 BAD_REQUEST \"No id has been provided!\""
}
And logging shows your ErrorHandler being called:
2023-07-24T11:25:49.185+01:00 DEBUG 71044 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler com.example.demo.ErrorHandler#handle(ResponseStatusException)
If you would like us to spend some more time investigating, please spend some time providing a complete yet minimal sample that reproduces the problem. You can share it with us by pushing it to a separate repository on GitHub or by zipping it up and attaching it to this issue.
Comment From: freid001-els
I'm not sure why but I get this response:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "No ids have been provided",
"instance": "/api/",
"properties": null
}