程序中对异常情况的处理

目前开发的一个项目

开发一个新功能,总是感觉很吃力,

因为总是要处理各种协作方接口异常情况:

(a)502 服务器没有启动

(b)403 拒绝访问

(c)404 接口路径不对

(d)500 服务器内部错误

如果把这些错误信息一层层往上返回,会非常麻烦

在业务逻辑中参杂了这些与业务一点关系都没有的代码,看起来很累赘.

看下面的代码:



 

 

 

错误是一步步往上传递,每一个方法里面都在处理,感觉好累

最下面的代码片段是控制器里面的,

在其他控制器里面也会看到类似的代码

其实可以统一处理的

这些异常应该在一个地方统一捕获,统一处理.

而不是东处理一个,西处理一个,看起来很乱,容易造成冗余和重复,很难维护.

下面我就漏改了:



 

如何实现异常统一处理呢?

第一,遇到异常直接抛出,而不是马上处理;

第二,一个异常handler进行统一处理

handler 类:

package com.chanjet.gov.handler;

import com.chanjet.gov.bean.exception.MustBeDealedException;
import com.chanjet.gov.util.Constant;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by whuanghkl on 3/30/16.
 */
//注意使用注解@ControllerAdvice作用域是全局Controller范围
//可应用到所有@RequestMapping类或方法上的@ExceptionHandler、@InitBinder、@ModelAttribute,在这里是@ExceptionHandler
@ControllerAdvice
public class ExceptionHandlerAdvice {
    @ExceptionHandler(MustBeDealedException.class)
//    @RESPONSE_CONTENTTYPE_JSON_UTFStatus(HttpStatus.BAD_REQUEST)
//    @ResponseBody
    public String handleIOException(MustBeDealedException ex) {
//        return ClassUtils.getShortName(ex.getClass()) + ex.getMessage();
       
        System.out.println(ex);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String responseStatusCode = ex.getResponseStatusCode();
        if (null == responseStatusCode) {
            responseStatusCode = Constant.EMPTY;
        }
        try {
            response.sendRedirect("/error.html?error=" + ex.getErrorCode() + "&responseStatusCode=" + responseStatusCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

参考:http://www.cnblogs.com/xguo/p/3163519.html

猜你喜欢

转载自hw1287789687.iteye.com/blog/2287966