1 Star 0 Fork 108

zhr0001 / spring-cloud-yes

forked from 大目 / spring-cloud-yes 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
统一异常管理.md 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
eacdy0000@126.com 提交于 2017-12-09 17:55 . 文档重新规划目录

统一异常管理

Spring Boot、Spring Cloud支持多种统一管理异常的方式,例如:

  • 继承org.springframework.boot.autoconfigure.web.BasicErrorController
  • ExceptionHandler

Spring Cloud YES中使用的是继承BasicErrorController 的方式,好处在于,使用这种方案,无需自己判断某个API是否AJax接口。示例代码如下:

@Controller
@RequestMapping("/error")
public class MyErrorController extends BasicErrorController {

    @Autowired
    public MyErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes, serverProperties.getError());
    }

    @RequestMapping(produces = "text/html")
    @Override
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        return super.errorHtml(request, response);
    }

    @RequestMapping
    @ResponseBody
    @Override
    @SuppressWarnings("unchecked")
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = super.getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));

        String message = body.get("message") != null ? (String) body.get("message") : null;
        Integer statusCode = body.get("status") != null ? (Integer) body.get("status") : null;

        Object exception = body.get("exception");
        if (exception != null && exception instanceof BizRuntimeException) {
            BizRuntimeException bre = (BizRuntimeException) exception;
            statusCode = bre.getCode();
        }

        AjaxResult<Object> build = AjaxResult.builder()
                .status(statusCode)
                .error(message)
                .message(message)
                .data(body)
                .build();
        Map res = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            String s = mapper.writeValueAsString(build);
            res = mapper.readValue(s, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpStatus status = super.getStatus(request);
        return new ResponseEntity<Map<String, Object>>(res, status);
    }
}
Java
1
https://gitee.com/hwzhang0916/spring-cloud-yes.git
git@gitee.com:hwzhang0916/spring-cloud-yes.git
hwzhang0916
spring-cloud-yes
spring-cloud-yes
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891