只需要加上一个controller,代码如下:
package com.wdlx.filter; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.AbstractErrorController; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/error") public class GlobalErrorController extends AbstractErrorController { @Autowired public GlobalErrorController(ErrorAttributes errorAttributes) { super(errorAttributes); } @Override public String getErrorPath() { return "/error"; } @RequestMapping(produces = MediaType.ALL_VALUE) public ResponseEntity error(HttpServletRequest request) { HttpStatus status = getStatus(request); if (status.is5xxServerError()) { // log maybe } return new ResponseEntity(status); } }
不过由于Spring Boot版本不同,比如我在1.3.5测试通过在1.4就不行,于是我去掉了
produces = MediaType.ALL_VALUE这个配置,就可以了