Simplifying Spring (Boot) ExceptionHandlers by extending ResponseStatusException

Featured image for sharing metadata for article

As mentioned in Simplifying Spring (Boot) ExceptionHandlers with ResponseStatus Annotations, one way we can set up HTTP exception handling us by annotating our exceptions with @ResponseStatus, and then using Reflection at runtime to map it to the HTTP response.

However, an even easier means of doing this is to have our on extend the ResponseStatusException:

import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatuson;

public class BadRequeston extends ResponseStatusException {
  public BadRequeston() {
    super(HttpStatus.BAD_REQUEST);
  }
}

When triggered, we get the default response:

HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sat, 12 Feb 2022 09:32:25 GMT
Connection: close
{
  "error": "Bad Request",
  "path": "/apis",
  "status": 400,
  "timestamp": "2022-02-12T09:32:25.537+00:00"
}

But we can also configure our exception to return i.e. Different HTTP headers, allowing us to have a more meaningful response:

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatuson;

public class ConflictException extends ResponseStatusException {

  private final String url;

  public ConflictException(String url) {
    super(HttpStatus.CONFLICT);
    this.url = url;
  }

  @Override
  public HttpHeaders getResponseHeaders() {
    HttpHeaders headers = new HttpHeaders();

    headers.add(HttpHeaders.LOCATION, url);

    return headers;
  }
}

Which responds with:

HTTP/1.1 409
Location: /apis/123
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sat, 12 Feb 2022 09:39:22 GMT
{
  "error": "Conflict",
  "path": "/apis",
  "status": 409,
  "timestamp": "2022-02-12T09:39:22.907+00:00"
}

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #spring-boot #spring.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.