Annotation Interface ResponseStatus


@Retention(RUNTIME) @Target({TYPE,METHOD}) public @interface ResponseStatus
Annotation for marking a class or method with the desired HTTP response status code and optional reason. When applied to a method or exception, the specified HTTP status code and reason will be used for the response. When both ResponseEntity and @ResponseStatus are used in a controller method, the HTTP status from ResponseEntity takes precedence over the one specified by @ResponseStatus.

Example usage:

1. Applied to a method:

 
 @ResponseStatus(HttpStatus.CREATED)
 public String createResource() {
        // Method implementation
      }
    

 This sets the HTTP response status code to 201 (Created) for the annotated method.
 
2. Custom Exception Usage:
    
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public class CustomAppException extends RuntimeException {

        // Constructors...
    }
  
  
    
    @GetMapping("/example")
    public String exampleEndpoint() {
        // Some logic that might throw the custom exception
        if (true) {
            throw new CustomAppException("Custom exception occurred.");
        }
        // Rest of the method logic
        return "Success";
    }
  
 
In this example, if the condition is met and the CustomAppException is thrown, the response will have a status of 500 (INTERNAL_SERVER_ERROR). You can customize the CustomAppException class to include any additional information you need in your application-specific exceptions.

Note: If a reason is provided, it will be included in the response alongside the status code.

Since:
1.0
Author:
Blyzhnytsia Team
See Also:
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    The optional reason associated with the response status.
    The HTTP response status code.
  • Element Details

    • value

      HttpStatus value
      The HTTP response status code.
      Returns:
      The HTTP status code (default is INTERNAL_SERVER_ERROR).
      Default:
      INTERNAL_SERVER_ERROR
    • reason

      String reason
      The optional reason associated with the response status.
      Returns:
      The reason for the response status (default is an empty string).
      Default:
      ""