自定义返回格式
package com.example.demo.entity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
@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;
@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());
}
}