Error Handling for REST API in SpringBoot with Response Status

When I was writing the base code in Spring boot for my RESTifying the ZFS APIs project, I was looking for some way of throwing the exception to the user with HTTP error code.

I found a way to handle it by using ResponseStatusExceptionResolver.

ResponseStatusExceptionResolver is introduced with Spring 3, and Its main responsibility is to use the @ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.

@ResponseStatus annotation

I created a ValidationException class extending the RuntimeException class with a constructor.

This is how my code looks like

package in.asvignesh.zfsservice.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

 * Created by asvignesh on 8/19/2019
public class ValidationException extends RuntimeException {

  public ValidationException(Throwable cause) {

And in the controller, I have a validate input blocks, which will throw ValidationException in case any error in input.

Also published on Medium.

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a ReplyCancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.