zoukankan      html  css  js  c++  java
  • RestControllerAdvice 全局异常处理

    //返回的json格式数据

    1:RestControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping、@PostMapping, @GetMapping注解中
    
    
    @RestControllerAdvice(basePackages ="com.zsc.tbpractice.controller" )
    public class GlobalExceptionHandler {
        private Log logger = LogFactory.getLog(GlobalExceptionHandler.class);

    2:
    ExceptionHandler 标记为全局异常
        @ExceptionHandler(value = Exception.class)
    public JsonResult defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    String url = request.getRequestURI() + (StringUtil.isNotEmpty(request.getQueryString()) ? ("?" + request.getQueryString()) : "");
    JsonResult result = new JsonResult(false);
    result.setRet(500);
    result.setMsg("error");
    if (ex instanceof TokenException) {
    result.setMsg(ex.getMessage());
    } else if (ex instanceof SysException) {
    result.setRet(((SysException) ex).getErrorCode());
    result.setMsg(ex.getMessage());
    } else if (ex instanceof NoHandlerFoundException) {
    NoHandlerFoundException notFindEx = (NoHandlerFoundException)ex;
    result.setRet(404);
    result.setMsg("找不到该接口: "+ JsonUtils.toStringNoEx(notFindEx));
    } else if (ex instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
    result.setRet(403);
    result.setMsg("不支持该请求方式");
    } else {
    result.setMsg("对不起!服务器趴窝了!" + ex.getClass().getName()+">>>>"+ex.getMessage());
    ex.printStackTrace();
    }
    logger.error("运行异常: "+result.getMsg());
    return result;
    }
    }
  • 相关阅读:
    P4559 [JSOI2018]列队
    2019.2.14 考试T3 交互题
    2019.2.14 考试T1 FFT
    P3240 [HNOI2015]实验比较 树形DP
    bzoj 3514: Codechef MARCH14 GERALD07加强版 LCT+主席树
    P4172 [WC2006]水管局长 LCT维护最小生成树
    P4177 [CEOI2008]order 最小割
    CF1073G Yet Another LCP Problem SA+权值线段树
    CF1110D Jongmah
    2019.2.10考试T2, 多项式求exp+生成函数
  • 原文地址:https://www.cnblogs.com/draymond/p/11429216.html
Copyright © 2011-2022 走看看