八、统一异常处理

一、消息数据统一返回给前台的处理方法
 1、新建一个公共Result<T>类包含 code、msg、data私有变量,并提供set 和get 方法。(固定格式)
/**
 * http请求返回的最外层对象
 */
public class Result<T> {
    /*错误码*/
    private Integer code;
    /*提示信息*/
    private  String msg;
    /*具体内容*/
    private T data;

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
}
2、新建一个ResultUtil工具类,编写静态方法,统一调用这个方法向前台返回

/**
 * 前端访问数据返回处理工具类
 * 依赖Result类
 */
public class ResultUtil {
    /**
     * 带数据的成功返回的方法
     * @param object 数据对象
     * @return
     */
    public static Result success(Object object){
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        result.setData(object);
        return result;
    }

    /**
     * 不带数据的成功返回的方法
     * @return
     */
    public static Result success(){
        Result result = new Result();
        result.setCode(0);
        result.setMsg("成功");
        return result;
    }

    /**
     * 返回失败的方法
     * @param code 错误代码
     * @param msg   返回消息
     * @return
     */
    public static Result error(Integer code,String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}
二、通过异常统一处理返回给前台的处理方法
 1、创建一个枚举,统一管理返回的code和message(相当于配置文件)
package com.du.enums;

/**
 * 用来统一管理异常的code 和message
 */
public enum ResultEnum {
    UNKONW_ERROR(-1,"未知错误"),
    SUCCESS(0,"成功"),
    PRIMARY_SCHOOL(100,"你可能在上小学"),
    MIDDLE_SCHOOL(101,"你可能在上初中"),
    ;
    private Integer code;

    private String  message;

    ResultEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }}
2、定义一个自己的异常,自定义返回数据格式
package com.du.Exception;

import com.du.enums.ResultEnum;

public class GrilException extends RuntimeException{
    //spring框架仅仅对RuntimeException抛出的异常进行回滚,
    //Exception不会所以继承该异常
    private Integer code;

    public GrilException(ResultEnum resultEnum) {
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}
3、进行捕获异常获取数据,未知错误情况下打印日志
package com.du.handle;

import com.du.Exception.GrilException;
import com.du.domain.Result;
import com.du.utils.ResultUtil;
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;


/**
 *handle包必须和controller、service包同级,
 * 这样controller中抛出异常的时候才会被自动调用
 */
@ControllerAdvice//增强型控制器,对于控制器的全局配置放在同一个位置
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    
    @ExceptionHandler(value=Exception.class)//捕获的异常类型
    @ResponseBody//没有@RestController这样写向前台返回数据
    public Result handle(Exception e){
        if(e instanceof GrilException){//判断异常是否为自定义的
            GrilException grilException = (GrilException) e;
            return  ResultUtil.error(grilException.getCode(),grilException.getMessage());
        }else{
            logger.error("【系统异常】{}",e);
            return ResultUtil.error(-1,"未知错误");
        }
  }
}

 

posted @ 2019-03-21 01:03  杜小二  阅读(249)  评论(0编辑  收藏  举报