SpringMVC+@ControllerAdvice全局异常处理


SpringMVC+@ControllerAdvice全局异常处理

@ControllerAdvice

spring3.2,增加了新注解@ControllerAdvice,控制器增强的注解。其原理是使用AOP对Controller控制器进行增强(前置增强、后置增强、环绕增强,AOP原理请自行查阅);这样我们就可以自行对控制器的方法进行调用前(前置增强)和调用后(后置增强)的处理。
@ControllerAdvice对所有Controller进行切面通知,可以指定父类

配合@ExceptionHandler实现全局异常处理

import com.zwq.ssm.constant.PropertyMsg;
import com.zwq.ssm.exception.AuthenticateException;
import com.zwq.ssm.exception.InvalidSessionException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: 全局异常处理
 *
 * @author zwq
 * @date 2021/9/8 14:58
 */
@ControllerAdvice
public class GlobalExceptionHandler {

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

    @ExceptionHandler(InvalidSessionException.class)
    @ResponseBody
    public ModelAndView invalidSessionException(InvalidSessionException e, HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("/login");
    }


    @ExceptionHandler(AuthenticateException.class)
    @ResponseBody
    public PropertyMsg authenticateException(AuthenticateException e, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("自定义异常");
        System.out.println(e.getCode());
        System.out.println(e.getMessage());
        return PropertyMsg.wrong(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public PropertyMsg unauthorizedException(UnauthorizedException e, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("没有权限");
        return PropertyMsg.wrong("没有权限");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public PropertyMsg exceptionHandler(Exception e, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("全局异常");
        return PropertyMsg.wrong("服务器异常");

    }
}

使用@ResponseBody表示返回JSON数据

数据返回集合:

import java.util.List;

/**
 * description: 数据返回规范
 *
 * @author zwq
 * @date 2021/7/11 9:42
 */
public class PropertyMsg {

    private int code;
    private int count;
    private Object data;
    private String msg;

    /**
     * description: 无数据成功返回
     * @author zwq
     * @date 2021/9/8 20:45
     * @param
     * @return com.zwq.websocket2.constants.Sms
     */
    public static PropertyMsg ok(){
        return new PropertyMsg(0, 1000, null, "操作成功");
    }

    /**
     * description: 一般数据成功返回
     * @author zwq
     * @date 2021/7/11 10:06
     * @param data 返回数据
     * @return com.zwq.websocket2.constants.Sms
     */
    public static PropertyMsg ok(Object data){
        return new PropertyMsg(0, 1000, data, "操作成功");
    }

    /**
     * description: 自定义消息成功返回
     * @author zwq
     * @date 2021/9/8 20:58
     * @param obj
     * @param msg
     * @return com.zwq.websocket2.constants.Sms
     */
    public static PropertyMsg okMsg(Object obj,String msg){
        return new PropertyMsg(0, 1000, obj, msg);
    }

    /**
     * description: 无数据失败返回
     * @author zwq
     * @date 2021/9/8 21:33
     * @param msg 信息
     * @return com.zwq.websocket2.constants.Sms
     */
    public static PropertyMsg wrong(String msg){
        return new PropertyMsg(1, 1000, null, msg);
    }

    /**
     * description: 一般数据失败返回
     * @author zwq
     * @date 2021/9/8 21:34
     * @param obj 数据
     * @param msg 信息
     * @return com.zwq.websocket2.constants.Sms
     */
    public static PropertyMsg wrong(Object obj,String msg){
        return new PropertyMsg(1, 1000, obj, msg);
    }


    public PropertyMsg() {
    }

    public PropertyMsg(int code, int count, Object data, String msg) {
        this.code = code;
        this.count = count;
        this.data = data;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

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

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

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

    @Override
    public String toString() {
        return "PropertyMsg{" +
                "code=" + code +
                ", count=" + count +
                ", data=" + data +
                ", msg='" + msg + '\'' +
                '}';
    }
}

自定义异常

/**
 * description: 全局异常
 * @author zwq
 * @date 2021/11/23 13:37
 */
public class AuthenticateException extends RuntimeException{
    private Integer code;
    public AuthenticateException(String msg) {
        super(msg);
        this.code=1;
    }

    public Integer getCode() {
        return code;
    }

}

  目录