Mastering @ResponseStatus in Spring Boot: Real‑World Examples & Custom Error Handling
This tutorial explains how Spring Boot's @ResponseStatus annotation works, demonstrates practical ways to throw ResponseStatusException, create custom exception classes, annotate controller methods, and replace the default error view with a custom JSON response, complete with code samples and diagrams.
Environment
SpringBoot 2.7.16
1. Introduction
The @ResponseStatus annotation can be placed on a method or an exception class to specify the HTTP status code and reason that should be returned. When a handler method is invoked, the status code is applied to the HTTP response, overriding any status set by ResponseEntity or a redirect.
Note: When used on an exception class or when the reason attribute is set, Spring uses HttpServletResponse.sendError , which treats the response as complete and may generate an HTML error page—unsuitable for REST APIs. In such cases, use ResponseEntity instead.
Controllers themselves can also be annotated with @ResponseStatus , and all @RequestMapping and @ExceptionHandler methods in the class inherit the status unless overridden locally.
2. Practical Cases
2.1 Directly Throwing ResponseStatusException
<code>@GetMapping("/list")
public Object list() {
ResponseStatusException responseStatusException = new ResponseStatusException(HttpStatus.OK, "就当请求成功了吧");
throw responseStatusException;
}
</code>2.2 Using @ResponseStatus on a Custom Exception Class
<code>@ResponseStatus(code = HttpStatus.FORBIDDEN, reason = "参数错误")
public class PackException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PackException(String message) {
super(message);
}
}
</code>Controller method:
<code>@GetMapping("/{id}")
public Object query(@PathVariable("id") Long id) {
if (id == 0L) {
throw new PackException("参数错误");
}
return "query - " + id;
}
</code>2.3 Using @ResponseStatus on a Controller Method
<code>@GetMapping("/status")
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "自定义错误信息")
public Object status() {
return "success";
}
</code>3. Customizing Error Content
Spring Boot registers a default error view (StaticView) that renders when an exception occurs and no specific error page is found. The flow is:
Controller throws an exception; ResponseStatusExceptionResolver resolves it and sets the status and reason.
The request is forwarded to the default error path /error , handled by BasicErrorController .
If no custom error page exists, Spring uses the automatically configured StaticView .
To replace the default view, define a bean named error that returns a custom View implementation:
<code>@Bean(name = "error")
View packError() {
return new View() {
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
Map<String, Object> infos = new HashMap<>();
infos.put("code", -1);
infos.put("errorMsg", request.getAttribute("javax.servlet.error.message"));
out.append(new ObjectMapper().writeValueAsString(infos));
out.close();
}
@Override
public String getContentType() {
return "text/html";
}
};
}
</code>The custom view returns a JSON payload containing the error code and the message extracted from the request attributes, demonstrating how to output the reason configured in @ResponseStatus .
That concludes the article; hope it helps.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.