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;
    }
    }
  • 相关阅读:
    Spring security 浅谈用户验证机制
    Spring Boot Oauth2
    解决端口被占用问题
    Intellij idea run dashboard面板
    深入了解Vue组件 — Prop(上)
    深入了解Vue组件 — 组件注册
    使用命令行工具创建Vue项目
    Vue.js — 组件基础
    Vue.js — 表单输入绑定
    Vue.js — 事件处理
  • 原文地址:https://www.cnblogs.com/draymond/p/11429216.html
Copyright © 2011-2022 走看看