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.

Default image
Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India

Leave a Reply

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