Spring Boot 2グローバル異常処理

22288 ワード

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 [email protected]
 * @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 [email protected]
 * @date   2018/4/13 14:08
 */
public class Rjson implements Serializable{

    /**
     * ajax200      */
    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.*;

/**
 * 
 *      
 * 
 *
 * @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