Skip to content
Advertisement

Spring Boot get JSON Error representation in the ErrorController

Spring Boot provides errors in the json format like this:

{
  "timestamp": "2019-01-17T16:12:45.977+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "Error processing the request!",
  "path": "/endpoint"
}

Is it possible for me to obtain this error inside the ErrorController and to proceed with it?

@Controller
public class CustomErrorController implements ErrorController {

@RequestMapping("/error")
public String handleError(Model model) {
    // how to get json-error here?
    model.addAttribute("resultJson", ?);
    return "error";
  }
}

Is it inside the HttpServletResponse or maybe something else?

Advertisement

Answer

The default error attributes are extracted from a WebRequest using the ErrorAttributes bean.

Spring already provided a default implementation of this bean, the DefaultErrorAttributes bean.

You can have this bean injected by the container, as any usual bean, to your custom /error controller implementation so you can use it:

@Controller
@RequestMapping({"/error"})
public class CustomErrorController extends AbstractErrorController {

    public CustomErrorController(final ErrorAttributes errorAttributes) {
        super(errorAttributes, Collections.emptyList());
    }

    @RequestMapping
    public String handleError(Model model, HttpServletRequest request) {
        Map<String, Object> errorAttributes = this.getErrorAttributes(request, false); // retrieve the default error attributes as a key/value map (timestamp, status, error...)
        // ...
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

Update (by @Igorz)

As of Spring Boot version 2.3.0

org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes(HttpServletRequest, boolean, boolean, boolean)

has been deprecated in favor of:

org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes(HttpServletRequest, ErrorAttributeOptions)

Static factory ErrorAttributeOptions.defaults() can be used as default ErrorAttributeOptions argument of above method.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement