在springboot开发中经常会遇到接口异常,如果没有特别处理,就会给一个大白板
这个就很不友好了,查看具体问题还需要去后台看日志
专业的做法是在Controller层统一做一次异常的捕捉和处理
一、异常枚举类
首先定义一个异常枚举类,用来存放所有异常,实际用的时候可以酌情增减
public enum ResponseEnum { SUCCESS("0000","调用成功"), ERROR1("0001","空指针异常"), ERROR2("0002","数字转换异常"), ERROR3("0003","数组越界异常"), ERROR4("0004","参数异常"), ERROR5("0005","请求方法异常"), ERROR9999("9999","其他异常"); private final String returnCode; private final String returnMessage; ResponseEnum(String returnCode, String returnMessage) { this.returnCode = returnCode; this.returnMessage = returnMessage; } public String getReturnCode() { return returnCode; } public String getReturnMessage() { return returnMessage; } }
二、返回值工具类
所有接口的返回值都要包含返回码和返回message,写个工具类统一处理
public class BaseResultUtils { public static BaseResponse setResult(String code, String msg, Object data) { return new BaseResponse(code, msg, data); } public static BaseResponse setResult(String code, String msg) { return setResult(code, msg, null); } public static BaseResponse success(Object data){ return setResult(SUCCESS.getReturnCode(),SUCCESS.getReturnMessage(),data); } public static BaseResponse error(ResponseEnum responseEnum) { return setResult(responseEnum.getReturnCode(),responseEnum.getReturnMessage()); } }
三、统一的返回格式类
所有返回的字符串里都包含这三个部分:returnCode 、returnMessage和data
@EqualsAndHashCode(callSuper = false) public class BaseResponse<T> implements Serializable { @ApiModelProperty("状态码") private String returnCode ; /** * 业务码描述 */ @ApiModelProperty("返回提示") private String returnMessage ; /** * 数据结果集 */ @ApiModelProperty("数据") private T data; public BaseResponse(String returnCode, String returnMessage, T data) { this.returnCode = returnCode; this.returnMessage = returnMessage; this.data = data; } }
四、异常拦截类
@ControllerAdvice @ResponseBody public class GlobalException { private final Logger logger = LoggerFactory.getLogger(GlobalException.class); @ExceptionHandler(value = {java.lang.NullPointerException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public BaseResponse nullPointerExceptionHandler(HttpServletResponse response, Exception e) { e.printStackTrace(); return BaseResultUtils.error(ERROR1); } /** * 其他异常 * * @param e * @return */ @ExceptionHandler(value = Exception.class) @ResponseBody public BaseResponse exceptionHandler(Exception e) { e.printStackTrace(); return BaseResultUtils.error(ERROR9999); } }
这样不管接口又什么异常,都可以被捕捉到,可以给前端一些提示信息,比方参数写错了,请求方法写错了之类
具体的报错日志还是需要去后台查看