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.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering @ResponseStatus in Spring Boot: Real‑World Examples & Custom Error Handling

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

@GetMapping("/list")
public Object list() {
    ResponseStatusException responseStatusException = new ResponseStatusException(HttpStatus.OK, "就当请求成功了吧");
    throw responseStatusException;
}

2.2 Using @ResponseStatus on a Custom Exception Class

@ResponseStatus(code = HttpStatus.FORBIDDEN, reason = "参数错误")
public class PackException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    public PackException(String message) {
        super(message);
    }
}

Controller method:

@GetMapping("/{id}")
public Object query(@PathVariable("id") Long id) {
    if (id == 0L) {
        throw new PackException("参数错误");
    }
    return "query - " + id;
}

2.3 Using @ResponseStatus on a Controller Method

@GetMapping("/status")
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "自定义错误信息")
public Object status() {
    return "success";
}

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:

@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";
        }
    };
}

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javabackend-developmentSpring BootError Handling@ResponseStatus
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.