Springboot统一Response
约 675 字大约 2 分钟
2025-04-10
一、简介。
作用
SpringBoot中不用关心异常,不用显示的进行try/catch,代码美观
作用域
所有注解了@RequestMapping的控制器上,说白了就是Controller
拓展
可以加到类上,也可以加到类的方法上。
关于代码的几点说明
代码中的@Data注解是应用了Lombok,自动生成getter和setter方法;
json格式化工具是fastJson,也可以自己换别的;
异常中加入了写日志。
二、全局异常配置类。
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
//运行时异常
@ExceptionHandler(RuntimeException.class)
public String runtimeExceptionHandler(RuntimeException ex) {
log.error(resultFormat(1, ex));
return resultFormat(1, ex);
}
//空指针异常
@ExceptionHandler(NullPointerException.class)
public String nullPointerExceptionHandler(NullPointerException ex) {
System.err.println("NullPointerException:");
log.error(resultFormat(2, ex));
return resultFormat(2, ex);
}
//类型转换异常
@ExceptionHandler(ClassCastException.class)
public String classCastExceptionHandler(ClassCastException ex) {
log.error(resultFormat(3, ex));
return resultFormat(3, ex);
}
//IO异常
@ExceptionHandler(IOException.class)
public String iOExceptionHandler(IOException ex) {
log.error(resultFormat(4, ex));
return resultFormat(4, ex);
}
//未知方法异常
@ExceptionHandler(NoSuchMethodException.class)
public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
log.error(resultFormat(5, ex));
return resultFormat(5, ex);
}
//数组越界异常
@ExceptionHandler(IndexOutOfBoundsException.class)
public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
log.error(resultFormat(6, ex));
return resultFormat(6, ex);
}
//400错误
@ExceptionHandler({HttpMessageNotReadableException.class})
public String requestNotReadable(HttpMessageNotReadableException ex) {
log.error(resultFormat(7, ex));
System.out.println("400..requestNotReadable");
return resultFormat(7, ex);
}
//400错误
@ExceptionHandler({TypeMismatchException.class})
public String requestTypeMismatch(TypeMismatchException ex) {
log.error(resultFormat(8, ex));
System.out.println("400..TypeMismatchException");
return resultFormat(8, ex);
}
//400错误
@ExceptionHandler({MissingServletRequestParameterException.class})
public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
log.error(resultFormat(9, ex));
System.out.println("400..MissingServletRequest");
return resultFormat(9, ex);
}
//405错误
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
public String request405(HttpRequestMethodNotSupportedException ex) {
log.error(resultFormat(10, ex));
return resultFormat(10, ex);
}
//406错误
@ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
public String request406(HttpMediaTypeNotAcceptableException ex) {
log.error(resultFormat(11, ex));
System.out.println("406...");
return resultFormat(11, ex);
}
//500错误
@ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
public String server500(RuntimeException ex) {
log.error(resultFormat(12, ex));
System.out.println("500...");
return resultFormat(12, ex);
}
//栈溢出
@ExceptionHandler({StackOverflowError.class})
public String requestStackOverflow(StackOverflowError ex) {
log.error(resultFormat(13, ex));
return resultFormat(13, ex);
}
//除数不能为0
@ExceptionHandler({ArithmeticException.class})
public String arithmeticException(ArithmeticException ex) {
log.error(resultFormat(13, ex));
return resultFormat(13, ex);
}
//其他错误
@ExceptionHandler({Exception.class})
public String exception(Exception ex) {
log.error(resultFormat(14, ex));
return resultFormat(14, ex);
}
private <T extends Throwable> String resultFormat(Integer code, T ex) {
log.error(JsonResult.failed(code, ex.getMessage()));
ex.printStackTrace();
log.error(String.format(logExceptionFormat, code, ex.getMessage()));
return JsonResult.failed(code, ex.getMessage());
}
}
三、JSON格式化输出
@Data
public class JsonResult implements Serializable {
private int code; //返回码 非0即失败
private String msg; //消息提示
private Map<String, Object> data; //返回的数据
public JsonResult() {
}
public JsonResult(int code, String msg, Map<String, Object> data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static String success() {
return success(new HashMap(0));
}
public static String success(Map<String, Object> data) {
return JSON.toJSONString(new JsonResult(0, "解析成功", data));
}
public static String failed() {
return failed("解析失败");
}
public static String failed(String msg) {
return failed(-1, msg);
}
public static String failed(int code, String msg) {
return JSON.toJSONString(new JsonResult(code, msg, new HashMap(0)));
}
}
四、controller测试代码
@RequestMapping("/zero")
@ResponseBody
public String zero() {
System.err.println("Controller测试");
String info = "除0异常";
int a = 1 / 0;
return info;
}