全局异常处理代码

直接上代码

package com.whfc.ms.exception;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultEnum;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sunguodong
 * @desc 全局异常处理
 * @date 2019-07-20
 */
@ControllerAdvice("com.whfc")
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Result exceptionHandler(Exception ex) {
        logger.error("not_handled_exception", ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg(ex.getMessage());
        return message;
    }

    @ExceptionHandler(value = {BizException.class})
    @ResponseBody
    public Result bizExceptionHandler(BizException ex) {
        logger.warn(ex.getMsg());
        Result message = new Result();
        message.setCode(ex.getCode());
        message.setMsg(ex.getMsg());
        return message;
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Result methodArgumentValidExceptionHandler(MethodArgumentNotValidException ex) {
        logger.warn(ex.getMessage());
        BindingResult result = ex.getBindingResult();
        List fieldErrors = new ArrayList<>();
        if (result.hasErrors()) {
            List errorList = result.getAllErrors();
            for (ObjectError error : errorList) {
                FieldError fieldError = (FieldError) error;
                fieldErrors.add(String.format("%s:%s", fieldError.getField(), fieldError.getDefaultMessage()));
            }
        }

        Result message = new Result();
        message.setCode(ResultEnum.PARAM_ERROR.getCode());
        message.setMsg(ResultEnum.PARAM_ERROR.getMessage());
        message.setData(fieldErrors);
        return message;
    }

    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    @ResponseBody
    public Result missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException ex) {
        logger.warn(ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.PARAM_ERROR.getCode());
        message.setMsg(String.format("缺少参数:%s,类型:%s", ex.getParameterName(), ex.getParameterType()));
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
    @ResponseBody
    public Result methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {

        logger.warn(ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.PARAM_ERROR.getCode());
        message.setMsg(String.format("参数%s类型不正确", ex.getName()));
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    @ResponseBody
    public Result httpMessageNotReadableException(HttpMessageNotReadableException ex) {

        logger.warn(ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.PARAM_ERROR.getCode());
        message.setMsg("参数格式不正确");
        message.setData(null);
        return message;
    }


    @ExceptionHandler(value = {AuthenticationException.class})
    @ResponseBody
    public Result authenticationException(AuthenticationException ex) {

        logger.warn(ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setData(null);
        message.setMsg("账号或密码错误");
        return message;
    }

    @ExceptionHandler(value = {AuthorizationException.class})
    @ResponseBody
    public Result authorizationException(AuthorizationException ex) {

        logger.warn(ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.AUTHZ_ERROR.getCode());
        message.setData(null);
        message.setMsg(ResultEnum.AUTHZ_ERROR.getMessage());
        return message;
    }

    @ExceptionHandler(value = {IncorrectCredentialsException.class})
    @ResponseBody
    public Result incorrectCredentialsException(IncorrectCredentialsException ex) {

        logger.warn(ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setData(null);
        message.setMsg("账号或密码错误");
        return message;
    }

}

自定义异常类 BizException

package com.whfc.common.exception;

/**
 * @Description:
 * @author: sunguodong
 * @version: 1.0
 * @date: 2019/7/22 14:43
 */
public class BizException extends RuntimeException {

    private String code;

    private String msg;

    public BizException() {
    }

    public BizException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

 

你可能感兴趣的:(JavaEE)