How to send a custom error message for bad requests (400 error code) in Spring Boot?

Let’s say you created a REST API which accepts a JSON input.

You handle any type of exception in your code and throw a custom error message to the user.

But what if the user sends a bad JSON ?

Spring framework will throw a predefined error message.

Below is the error message I got for supplying invalid JSON to a sample REST API I created:

In some cases different error messages could be returned .

Here is the REST API:

package com.badrequest.custommessage;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

@org.springframework.web.bind.annotation.RestController
public class RestController {



    @PostMapping("/poke")
    public Map<String,Object> poke(@RequestBody  Map<String,Object> request){

        Map<String,Object> response = new HashMap<String,Object>();

        try{


            response.put("request",request);
            response.put("status","success");


        }catch(Exception e){

            response.put("status","Your request is invalid");

        }

        return response;

    }
}

As you see I am just receiving the input and storing it another map along with the status and returning it back.

For any exception I am throwing a custom error message “Your request is invalid”.

What if I want to throw the same error message on a bad request.

It can’t be handled directly in the code as every exception is already caught using a try catch block inside the controller class.

This can be achieved by creating a Controller Advice.

Here is the controller advice class I created:

package com.badrequest.custommessage;

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

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    Map<String,String> showCustomMessage(Exception e){


        Map<String,String> response = new HashMap<>();
        response.put("status","Your input is invalid");

        return response;
    }
}

To throw a custom error message follow the below algorithm:

STEP1: Create a controller advice class

STEP2: Annotate it with @ControllerAdvice

STEP3: Create a method and return the custom error message in a map inside the method

STEP4: Annotate the method with @ExceptionHandler as this method handles exceptions

STEP5: Annotate the same method with @ResponseStatus(HttpStatus.BAD_REQUEST) as it deals with only 400 BAD REQUEST exceptions

STEP6: Annotate the same method with @ResponseBody to indicate that the response body to be returned for bad requests is supplied by this method.

After implementing it , when I hit the REST API it threw the custom error defined:

That’s it!


Posted

in

by

Tags:

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading