Returning Custom Status Codes from Spring Controllers

1. Overview

This quick article will demonstrate a few ways to return custom HTTP status codes from Spring MVC controllers.

This is often important in order to more clearly express the result of a request to a client and using the full rich semantics of the HTTP protocol. For example, if something goes wrong with a request, sending a specific error code for each type of possible problem would allow the client to display an appropriate error message to the user.

The setup of a basic Spring MVC project is outside the scope of this article, but you can find more information here.

2. Returning Custom Status Codes

Spring provides a few primary ways to return custom status codes from its Controller classes:

  • using a ResponseEntity
  • using the @ResponseStatus annotation on exception classes, and
  • using the @ControllerAdvice and @ExceptionHandler annotations.

These options are not mutually exclusive; far from it, they can actually complement one another.

This article will cover the first two ways (ResponseEntity and @ResponseStatus). If you would like to learn more about using @ControllerAdvice and @ExceptionHandler, you can read about it here.

2.1. Returning Status Codes via a ResponseEntity

In a standard Spring MVC controller, we will define a simple mapping:

@RequestMapping(value = "/controller", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity sendViaResponseEntity() {
    return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
}

Upon receiving a GET request to “/controller“, Spring will return a response with the 406 Code (Not Acceptable). We arbitrarily selected the specific response code for this example. You can return any HTTP status code (the full list can be found here).

2.2. Returning Status Codes via an Exception

We will add a second method to the controller to demonstrate how to use an Exception to return a status code:

@RequestMapping(value = "/exception", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity sendViaException() {
    throw new ForbiddenException();
}

Upon receiving a GET request to “/exception“, Spring will throw a ForbiddenException. This is a custom exception that we will define in a separate class:

@ResponseStatus(HttpStatus.FORBIDDEN)
public class ForbiddenException extends RuntimeException {}

No code is required in this exception. All the work is done by the @ResponseStatus annotation.

In this case, when the exception is thrown, the controller that threw it returns a response with the response code 403 (Forbidden). If necessary, you can also add a message in the annotation that will be returned along with the response.

In this case, the class would look like this:

@ResponseStatus(value = HttpStatus.FORBIDDEN, reason="To show an example of a custom message")
public class ForbiddenException extends RuntimeException {}

It is important to note that while it is technically possible to make an exception return any status code, in most cases it only makes logical sense to use exceptions for error codes (4XX and 5XX).

3. Conclusion

The tutorial showed how to return custom status codes from Spring MVC controllers.

The implementation can be found in the example GitHub project.

Related posts:

Request a Delivery / Read Receipt in Javamail
Java TreeMap vs HashMap
Mảng (Array) trong Java
Spring Boot - Sending Email
A Guide to the Java LinkedList
Java – File to Reader
Spring Boot - Building RESTful Web Services
Introduction to Thread Pools in Java
Introduction to the Java NIO2 File API
Java Program to Find Strongly Connected Components in Graphs
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
Lớp Collections trong Java (Collections Utility Class)
Một số nguyên tắc, định luật trong lập trình
Creating a Custom Starter with Spring Boot
Java Program for Topological Sorting in Graphs
Java Program to Implement Segment Tree
Java Program to Implement Adjacency Matrix
Java Program to Show the Duality Transformation of Line and Point
Giới thiệu Aspect Oriented Programming (AOP)
Spring WebClient vs. RestTemplate
Guide to the Volatile Keyword in Java
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Concurrent Test Execution in Spring 5
Thực thi nhiều tác vụ cùng lúc như thế nào trong Java?
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Java Program to Implement Hash Tables Chaining with List Heads
Java Program to subtract two large numbers using Linked Lists
Apache Commons Collections MapUtils
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Java Program to Implement a Binary Search Tree using Linked Lists
A Quick Guide to Using Keycloak with Spring Boot