项目规范统一是项目长久迭代的根本,规范统一可以让新入职或者新接手的人员能够迅速掌握项目结构,项目的整体设计,快速入手项目,提高开发效率的同时减少我们程序员兄弟的痛苦,今天就说一下异常统一处理,简单来说就是项目做统一处理。下面看一下代码,项目为springboot项目
一、自定义HandlerExceptionResolver 异常拦截,所有throw 出的异常都会经过这里被拦截,然后做统一的返回处理,这里返回的是json格式字符串
package com.activemq.activemq_product.expection;
@Configuration
public class AgentExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception exception) {
System.out.println("进来了,,,,,");
Map<String, Object> map = new HashMap<String, Object>();
try {
response.setContentType("application/json;charset=UTF-8");
PrintWriter writer = response.getWriter();
map.put("success", false);
if (exception instanceof CustomException) {
map.put("message", exception.getCause().getMessage());
map.put("code", exception.getMessage());
}
writer.write(JSONObject.toJSONString(map));
writer.flush();
writer.close();
return new ModelAndView("error");
} catch (IOException e) {
map.put("message","系统错误");
//异常中的异常返回到错误页面
return new ModelAndView("error", map);
}
}
}
二、自定义异常类,作为异常是返回异常类
package com.activemq.activemq_product.expection;
/**
*统一返回自定义的异常
*/
public class CustomException extends RuntimeException{
private static final long serialVersionUID = 1L;
public CustomException() {
super();
}
public CustomException(String message) {
super(message);
}
public CustomException(Throwable cause) {
super(cause);
}
public CustomException(String message, Throwable cause) {
super(message, cause);
}
public CustomException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
三、模拟异常测试
@RestController
public class ProducerController {
Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("/sendMsg")
public Map sendMsg(String msg) {
logger.info("msg==>:"+msg);
try {
//模拟异常
int a = 1/0;
}catch (Exception e){
//第一个参数为字符串 ,可以自定义错误码返回,也可以定义其他的,第二个是exception对象,方便查询错误信息。
throw new CustomException("10000",e);
}
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("msg",msg);
return resultMap;
}
}
此时结果截图: 统一返回格式,错误码,错误信息,是否成功等,根据需要自己进行修改