LoginSignup
21
22

More than 5 years have passed since last update.

Spring Boot な REST API でエラーが発生した際に返すJSONはどこで誰が作ってる???

Last updated at Posted at 2015-06-03

こんなやつ。カスタマイズしたいのだが、どこでやってるのか見当もつかず。

$ curl -H "X-DDD: 777" localhost:8080/rest/v2/hoge/moges/2828 | jq '.'
{
  "timestamp": "2014-12-03T19:37:09.918+0900",
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.ServletRequestBindingException",
  "message": "Missing request header 'X-DDD' for method parameter of type Long",
  "path": "/rest/v2/hoge/moges/2828"
}

org.springframework.boot.autoconfigure.web.BasicErrorController ってのがあって、そこでやってた。

BasicErrorController.java
private final ErrorAttributes errorAttributes;

@RequestMapping(value = "${error.path:/error}")
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
    HttpStatus status = getStatus(request);
    return new ResponseEntity<Map<String, Object>>(body, status);
}

private Map<String, Object> getErrorAttributes(HttpServletRequest request,
        boolean includeStackTrace) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    return this.errorAttributes.getErrorAttributes(requestAttributes,
            includeStackTrace);
}

org.springframework.boot.autoconfigure.web.ErrorAttributes はインターフェースで、同パッケージに存在する DefaultErrorAttributes を使っているみたい。

DefaultErrorAttributesのインスタンスは、BasicErrorController のコンストラクタで受け取るようになってて、DefaultErrorAttributesのインスタンス生成がポイント。

で、実際にやってるのは org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration。これなら上書きできそうだ。

ErrorMvcAutoConfiguration.java

@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes();
}

@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
    return new BasicErrorController(errorAttributes);
}

21
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
22