3.5 定义通用的返回对象-异常处理02 1. 为 handlerException() 方法继续添加 @ResponseBody 注解即可将返回的 object 返回给前端页面。 该方式会将异常的所有栈信息序列化后输出到前端页面,因此还需要继续处理,只将前端需要的异常信息返回给前端。 2. 将 ex 强转为 BusinessException ,然后使用其 getErrCode、getErrMsg 方法获取前端需要的异常信息,将其封装为 Map 后封装到 CommonReturnType 对象中,然后再返回给前端。 3. 优化:使用 CommonReturnType 的静态方法 create 构造对象并返回。 4. 继续完善该方法。 判断 exception 是否为 BusinessException 类型,如果不是则为 CommonReturnType 对象赋值 errCode 为 EmBusinessError 枚举中的 UNKNOWN_ERROR 的 code 和 msg。 5. 继续优化异常处理。 因为该处理方式是所有 controller 都需要的方式,因此将其抽象为 BaseController 中的方法,然后让其他 controller 组件去继承该 controller。 6. 总结:a. 定义一个 CommonReturnType, 能够用对应的 status, object 的方式返回所有的被 JSON 序列化对象,供前端解析使用,摒弃掉了使用 httpstatuscode + 内线 tomcat 自带的 error 页面方式去处理响应数据以及异常。 b. 并且定义了一个 BusinessException ,统一管理我们自定义的错误码。 c. 然后,在 BaseController 中定义一个所有 Controller 的基类,使用其中注解了 @ExceptionHandler 的方法来处理所有被 Controller 层捕获的异常。 按照异常的种类由2种处理方式,一种是自定义 BusinessException, 其中有自定义的 error 的 code 和 msg,一种是未知的异常,采用统一处理方式。 d. 异常处理方法上还可以添加日志相关组件,方便项目运行记录与错误排查。
Enum 中的 int 类型的状态码,如果以 0 开头,则会在 controller 组件中返回到前端时,如果使用了 JSON 序列化,解析时则会省略数字前的 0,因此,不应该使用 0 开头。
正例:10001、10002、20001
反例:00001、00002
SpringBoot的异常处理方法
返回的data返回的是exception异常类的反序列化json,强转成BusinessException
//定义exceptionhandler解决未被controller层吸收的exception异常 @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.OK) @ResponseBody public Object handlerException(HttpServletRequest request, Exception ex){ Map<String, Object> responseData = new HashMap<>(); if(ex instanceof BusinessException){ BusinessException businessException = (BusinessException)ex; responseData.put("errCode", businessException.getErrorCode()); responseData.put("errMsg", businessException.getErrMsg()); }else { responseData.put("errCode", EmBusinessError.UNKONW_ERROR.getErrorCode()); responseData.put("errMsg", EmBusinessError.UNKONW_ERROR.getErrMsg()); } return CommonReturnType.create(responseData, "fail"); }
首先定义一个commonReturnType,能够用status和data返回所有json序列化方式的所有的固定的对象,供前端解析使用。摒弃tomca和http自带err页处理。定义common的BusinessErr方式统一管理想要的错误码。然后在baseController中定义通用exceptionhandler类解决未被controller层吸收的exception,并且使用errcode和errmsg统一的方式吃掉了所有内部不可预知的异常
利用Springboot的@ExceptionHandle解决未被controller层吸收的exception,从而实现统一的异常处理。
异常类处理