javaweb 统一异常处理

        项目规范统一是项目长久迭代的根本,规范统一可以让新入职或者新接手的人员能够迅速掌握项目结构,项目的整体设计,快速入手项目,提高开发效率的同时减少我们程序员兄弟的痛苦,今天就说一下异常统一处理,简单来说就是项目做统一处理。下面看一下代码,项目为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;
    }
}

此时结果截图: 统一返回格式,错误码,错误信息,是否成功等,根据需要自己进行修改

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值