Spring Boot 2 全局异常处理

1、创建 MyRestControllerAdvice 类,并添加 @RestControllerAdvice
import com.tm.common.dto.Rjson;
import com.tm.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DataAccessException;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 增强器
 * 还有一个 @ControllerAdvice,
 * 他们的区别类似于:@RestController @Controller的区别
 * 如果用:@ControllerAdvice,那么以下发方法,就要加 @ResponseBody 返回数据
 * @author tomao2014@qq.com
 * @date   2018/5/22 21:09
 */
@Slf4j
@RestControllerAdvice
public class MyRestControllerAdvice {

    @ExceptionHandler(RuntimeException.class)
    public Rjson handleRuntimeException(RuntimeException e){
        // http请求异常
        if (e instanceof HttpMessageConversionException){
            log.error("Bad Request",e.getMessage(),e);
            return Rjson.error("Bad Request");
        }
        if (e instanceof AuthorizationException){
            log.error("【无操作权限Shiro",e.getMessage(),e);
            return Rjson.error(Rjson.CODE_1403,"未授权:操作失败,请联系管理员授权");
        }
        if (e instanceof BusinessException){
            log.error("【业务异常】",e.getMessage(),e);
            return Rjson.error(e.getMessage());
        }
        if (e instanceof DataAccessException){
            log.error("【数据库异常:spring-dao",e.getMessage(),e);
            return Rjson.error("DB异常,请联系管理员");
        }
        log.error("【其他RuntimeException",e.getMessage(),e);
        return Rjson.error();
    }


    /** 全局异常捕捉处理 */
    @ExceptionHandler(Exception.class)
    public Rjson handleException(Exception e){
        if (e instanceof  HttpRequestMethodNotSupportedException){
            return Rjson.error("不支持的请求方式/"+e.getMessage());
        }
        log.error("【未知异常】:"+e.getMessage(), e);
        return Rjson.error();
    }
}

2、创建通用,统一的的返回对象
import java.io.Serializable;

/**
 * 通用的返回对象
 * @author tomao2014@qq.com
 * @date   2018/4/13 14:08
 */
public class Rjson implements Serializable{

    /**
     * ajax响应编码,200 表示正常请求,不存在非授权或者未登录请求
     */
    public static final int CODE_DEF = 200;

    /**
     * 未登录,前端判断后,跳转到登录页面
     */
    public static final int CODE_1100 = 1100;

    /**
     * 无权访问
     */
    public static final int CODE_1403 = 1403;

    private Integer code = CODE_DEF;

    private Boolean success = false;

    private String msg;

    private Object obj;

    public Integer getCode() {
        return code;
    }

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

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public String getMsg() {
        return msg;
    }

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

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public static Rjson error(){
        Rjson r = new Rjson();
        r.setMsg("系统异常,请稍后重试");
        return r;
    }
    public static Rjson error(String msg){
        Rjson r = new Rjson();
        r.setMsg(msg == null ? "系统异常,请稍后重试" : msg);
        return r;
    }
    public static Rjson error(int code,String msg){
        Rjson r = new Rjson();
        r.setCode(code);
        r.setMsg(msg == null ? "系统异常,请稍后重试" : msg);
        return r;
    }
    public static Rjson ok() {
        Rjson r = new Rjson();
        r.setSuccess(true);
        return r;
    }
    public static Rjson ok(String msg) {
        Rjson r = new Rjson();
        r.setSuccess(true);
        r.setMsg(msg);
        return r;
    }
    public static Rjson ok(Object obj) {
        Rjson r = new Rjson();
        r.setSuccess(true);
        r.setObj(obj);
        return r;
    }
    public static Rjson ok(Object obj,String msg) {
        Rjson r = new Rjson();
        r.setSuccess(true);
        r.setObj(obj);
        r.setMsg(msg);
        return r;
    }
}
3、添加完上面的配置之后,我们在controller类中,可以不添加 try...catch... 模块了。
如果出现异常,那么会进入 MyRestControllerAdvice 处理,并返回对应的错误信息。前端页面不会看到
后台直接抛出的异常信息。
import com.baomidou.mybatisplus.mapper.Condition;
import com.tm.auth.entity.SysUser;
import com.tm.auth.service.SysUserService;
import com.tm.common.controller.BaseController;
import com.tm.common.dto.Rjson;
import com.tm.common.validator.ValidatorUtils;
import com.tm.common.validator.group.AddGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  用户管理
 * </p>
 *
 * @author tomao2014qq.com
 * @since 2018-05-18
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/add")
    public Rjson add(@RequestBody SysUser user){
        ValidatorUtils.validateEntity(user,AddGroup.class);
        sysUserService.add(user);
        return Rjson.ok();
    }
}
如果在controller类中添加了 try...catch... 如果处理过程中,出现异常,那么返回的是 controller
中我们指定catch中的信息。
@PostMapping("/add")
public Rjson add(@RequestBody SysUser user){
    try {
        ValidatorUtils.validateEntity(user,AddGroup.class);
        sysUserService.add(user);
    }catch (Exception e){
        return Rjson.error("返回的异常信息,是我!");
    }
    return Rjson.ok();
}

参考资料:

https://www.cnblogs.com/magicalSam/p/7198420.html

https://www.cnblogs.com/nosqlcoco/p/5562107.html

https://blog.csdn.net/flygoa/article/details/75284755


展开阅读全文

没有更多推荐了,返回首页