【springboot】全局异常统一处理

自定义返回格式

package com.example.demo.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

/**
 * @Description: 自定义数据返回格式
 * @Author: Lorogy
 * @Date: 2021/2/3 15:22
 */
@Data
public class JsonResult {
    
    
    private Integer code; //响应状态码
    private String msg; //响应消息
    private Object data; //响应数据

    public JsonResult(Integer code, String msg, Object data) {
    
    
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

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

    public static JsonResult build(Integer status, String msg, Object data) {
    
    
        JsonResult jsonResult = new JsonResult(status, msg, data);
        return jsonResult;
    }

    public static JsonResult build(Integer status, String msg) {
    
    
        JsonResult jsonResult = new JsonResult(status, msg);
        return jsonResult;
    }

    public static JsonResult ok( Object data) {
    
    
        JsonResult jsonResult = new JsonResult(200, "success", data);
        return jsonResult;
    }

    @Override
    public String toString() {
    
    
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",code);
        jsonObject.put("msg",msg);
        jsonObject.put("data",data);

        return JSON.toJSONString(jsonObject);
    }
}

全局异常处理

package com.example.demo.exception;

import com.example.demo.entity.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * @Description: 全局异常处理
 * @Author: Lorogy
 * @Date: 2021/2/3 15:33
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    
    
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResult errorHandler(HttpServletRequest request,
                                   HttpServletResponse response,
                                   Exception e) {
    
    
        e.printStackTrace();
        response.setCharacterEncoding("UTF-8");//防止返回中文乱码
        return JsonResult.build(response.getStatus(), e.getMessage());
    }
}

猜你喜欢

转载自blog.csdn.net/lorogy/article/details/113700008