Carla
Carla

Reputation: 3380

How to show Exception name in Spring Boot's JSON Response

I have a Spring Controller which may throw a Runtime Exception at a certain point:

@RequestMapping("/list")
public List<User> findAll() {
        // if here  
        throw new RuntimeException("Some Exception Occured");

}

When I request that URI, the JSON does not include the Exception name ("Runtime Exception"):

curl -s http://localhost:8080/list 
{
  "timestamp": "2020-04-01T13:15:11.091+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "Some Exception Occured",
  "path": "/list"
}

Is there way to have it included in the JSON which is returned? Thanks!

Upvotes: 0

Views: 318

Answers (1)

Francesco Marchioni
Francesco Marchioni

Reputation: 4328

I think you can do that by extending the DefaultErrorAttributes and provide a custom list of attributes to be displayed in the returned JSON. For example, the following one provides a custom error response for Field errors:

import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.context.MessageSource;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.WebRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;


public class ResolvedErrorAttributes extends DefaultErrorAttributes {

    private MessageSource messageSource;

    public ResolvedErrorAttributes(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
        resolveBindingErrors(errorAttributes);
        return errorAttributes;
    }

    private void resolveBindingErrors(Map<String, Object> errorAttributes) {
        List<ObjectError> errors = (List<ObjectError>) errorAttributes.get("errors");
        if (errors == null) {
            return;
        }

        List<String> errorMessages = new ArrayList<>();
        for (ObjectError error : errors) {
            String resolved = messageSource.getMessage(error,  Locale.US);
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                errorMessages.add(fieldError.getField() + " " + resolved + " but value was " + fieldError.getRejectedValue());
            } else {
                errorMessages.add(resolved);
            }
        }
        errorAttributes.put("errors", errorMessages);
    }
}

In this tutorial you can find some more details about Spring Boot custom error responses.

Upvotes: 1

Related Questions