HandlerExceptionResolver 全局异常

全局异常,出现异常时,两种场景

返回统一的错误页面。页面跳转


    ```
### 返回json数据,页面不跳转,比如提示系统异常,请重试。

```java
public class GlobalExceptionResolver implements HandlerExceptionResolver
{
    private final static Logger LOGGER = LoggerFactory
        .getLogger(IntentionServiceImpl.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex)
    {
       LOGGER.error("ExternalRPCException--ex:{}", ex);
        Result result = new Result();
        result.setSuccess(false);
        if (ex instanceof ExternalRPCException)
        {
            ExternalRPCException exception = (ExternalRPCException)ex;
            // int-->String ??
            result.setResultCode(ConvertUtil.strToInt(exception.getCode(), 0));
            result.setInfo(MessageSourceHelper.getMessage(exception.getCode()));
        }
        else
        {//统一系统异常
            result.setCode("80000");
            result.setInfo(MessageSourceHelper.getMessage("80000"));
        }
        response(result, response);
        //跳转到error视图
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("result",result);
//        modelAndView.setViewName("error/error");
        return new ModelAndView();
/**
* 主要是靠response.getWriter().flush();来实现。
* 可以实现一些eccdoe,
* HttpServletResponse  就可以实现一些header的属性设置等
/
private void response(Result result, HttpServletResponse response)
    {
        ModelMap modelMap = new ModelMap();
        Writer writer = null;
        try
        {
            writer = response.getWriter();
            result.flush(modelMap);//encode
            writer.write(JsonUtils.getJsonFromBean(modelMap));
            writer.flush();
        }
        catch (Exception e)
        {
            LOGGER.error("Execute responseexception:{}", e);
        }
        finally
        {
            IOUtils.closeQuietly(writer);
        }

代码中的Result 就是一个Map对象。换成其他任何对象都是一样的。一般都是统一接口的ResponseVO对象。

你可能感兴趣的:(spring)