Springboot全局异常处理GlobalExceptionHandler

一:创建【GlobalExceptionHandler】去解决上述问题;

1.创建【GlobalExceptionHandler】,去捕获、拦截、并处理Controller抛出的
异常;

//GlobalExceptionHandler类:

package com.ly.web.exception;

import cn.ponfee.disjob.common.exception.Throwables;
import cn.ponfee.disjob.common.model.Result;
import cn.ponfee.disjob.common.spring.RpcController;
import cn.ponfee.disjob.common.util.Jsons;
import cn.ponfee.disjob.core.base.JobCodeMsg;
import cn.ponfee.disjob.core.base.JobConstants;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.ServiceException;
import com.ly.common.utils.ServletUtils;
import com.ly.common.utils.security.PermissionUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 全局异常处理器
 *
 * @author ly
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常(ajax请求返回json,redirect请求跳转页面)
     */
    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request) {
        log.error("请求地址'{}',权限校验失败'{}'", request.getRequestURI(), e.getMessage());
        if (ServletUtils.isAjaxRequest(request)) {
            return AjaxResult.error(PermissionUtils.getMsg(e.getMessage()));
        } else {
            return new ModelAndView("error/unauth");
        }
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Object handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("业务异常", e);
        if (ServletUtils.isAjaxRequest(request)) {
            return AjaxResult.error(e.getMessage());
        } else {
            return new ModelAndView("error/service", "errorMessage", e.getMessage());
        }
    }

    /**
     * 请求路径中缺少必需的路径变量
     */
    @ExceptionHandler(MissingPathVariableException.class)
    public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
        log.error("请求路径中缺少必需的路径变量:path={},error={}", request.getRequestURI(), e.getMessage());
        return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e,
                                                                HttpServletRequest request) {
        log.error("请求参数类型不匹配:path={},error={}", request.getRequestURI(), e.getMessage());
        return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType(), e.getValue()));
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException e) {
        return AjaxResult.error(e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Throwable.class)
    public void handleException(HandlerMethod handlerMethod,
                                HttpServletRequest request,
                                HttpServletResponse response,
                                Throwable t) throws IOException {
        log.error("系统异常", t);

        String errorMsg = Throwables.getRootCauseMessage(t);
        response.setCharacterEncoding(JobConstants.UTF_8);
        PrintWriter out = response.getWriter();
        if (isResponseJson(handlerMethod, request)) {
            response.setContentType(JobConstants.APPLICATION_JSON_UTF8);
            Object result;
            if (Result.class.isAssignableFrom(handlerMethod.getMethod().getReturnType())) {
                result = Result.failure(JobCodeMsg.SERVER_ERROR.getCode(), errorMsg);
            } else {
                result = AjaxResult.error(errorMsg);
            }
            errorMsg = Jsons.toJson(result);
        } else {
            response.setContentType(JobConstants.TEXT_PLAIN_UTF8);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        out.write(errorMsg);
        out.flush();
    }

    // -----------------------------------------------------------------------------private methods

    private static boolean isResponseJson(HandlerMethod handlerMethod, HttpServletRequest request) {
        if (handlerMethod == null ||
            handlerMethod.getBeanType() == BasicErrorController.class ||
            RpcController.class.isAssignableFrom(handlerMethod.getBeanType())) {
            return false;
        }

        return ServletUtils.isAjaxRequest(request);
    }

}

【@ControllerAdvice】注解;

          ●【@ControllerAdvice】相当于是一个Controller增强器,可对controller中被 @RequestMapping注解的方法(也就是Controller中,那些设置了url,可以接受并处理前端请求的方法),加一些逻辑处理;

          ● 即,如果Controller中的方法如果满足这两个条件:【这个方法使用了@RequestMapping、 @GetMapping或 @PosttMapping注解:也就是这个方法是一个设置了url,可以接受并处理前端请求的方法】+【这个方法抛出了异常】;;;;那么这个Controller中的方法,就会被【使用了@ControllerAdvice注解的,GlobalExceptionHandler类】给捕获;;;;;然后,就会根据【GlobalExceptionHandler类】中编写的具体内容,去拦截异常,给这个方法添加一些处理逻辑;(对于,这儿的情况来说,这个处理逻辑就是:提取异常信息,构建API统一返回对象;)

          ● 即,【@ControllerAdvice】注解的主要作用是:捕获;;;但是,只捕获,而不去处理可不行;;;所以,如果想要处理的话,就需要下面介绍的【@ExceptionHandler(Exception.class)】去拦截异常,并对其做相应的处理;

【@ExceptionHandler(Exception.class)】注解;

           ●【@ExceptionHandler】用来统一处理方法抛出的异常,可以给注解添加参数,参数是某个异常类的class,代表这个方法专门处理该类异常。

注意:

 ● @ControllerAdvice 捕获 Controller 层抛出的异常,如果添加 @ResponseBody 返回信息则为JSON格式。
● @RestControllerAdvice 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
 

以后我们如果在Service层遇到了异常后;Service层大胆的向上抛就行了,Controller接到这个异常后,也继续抛就行了,因为,我们上面编写的【GlobalExceptionHandler】会很友好的去处理这个异常,把其转化为API统一返回对象,以符合接口返回的格式;

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值