@ControllerAdvice -- 处理异常示例

Class : SessionInterceptor

package com.estate.web.filter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ucenter.api.exception.SessionException;
import com.ucenter.api.exception.SignatureException;
import com.ucenter.api.exception.TimeOutException;
import com.ucenter.api.session.bean.Result;
import com.ucenter.api.session.service.IWebSessionService;

public class SessionInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private IWebSessionService webSessionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从request中获取sessionid
        String sessionid = request.getParameter("sessionid");
        if (StringUtils.isBlank(sessionid)) {
            // 从cookies中获取sessionid
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("sessionid".equals(cookie.getName())) {
                        sessionid = cookie.getValue();
                    }
                }
            }
        }
        if (StringUtils.isBlank(sessionid))
            throw new SessionException();
        // 获取时间戳
        long timestamp = NumberUtils.toLong(request.getParameter("timestamp"), 0);
        if (timestamp <= 0)
            throw new TimeOutException();
        // 获取签名
        String signature = request.getParameter("signature");
        if (StringUtils.isBlank(signature))
            throw new SignatureException();
        // dubbo校验
        Result result = webSessionService.checkSessionid(sessionid, signature, timestamp);

        // 校验成功,将sessionid放入request对象中
        request.setAttribute("sessionid", sessionid);
        request.setAttribute("ecid", result.getEcid());
        request.setAttribute("uid", result.getUid());
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}

Class : GlobalExceptionHandler

package com.xindatai.ibs.web.exception;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ucenter.api.exception.SessionException;
import com.ucenter.api.exception.SignatureException;
import com.ucenter.api.exception.TimeOutException;
import com.xindatai.common.web.resp.BaseRespWriter;

@ControllerAdvice
public class GlobalExceptionHandler {
    public static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "IOException occured")
    @ExceptionHandler(IOException.class)
    @ResponseBody
    public void handleIOException() {
        // returning 404 error code
    }

    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ExceptionHandler(TimeOutException.class)
    public void timeOutException(HttpServletRequest request, HttpServletResponse response, TimeOutException ex) throws IOException {
        outputMessage(response, JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect));
        // return JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect);
    }

    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ExceptionHandler(SessionException.class)
    public void sessionException(HttpServletRequest request, HttpServletResponse response, SessionException ex) throws IOException {
        outputMessage(response, JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect));
        // return JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect);
    }

    // @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ExceptionHandler(SignatureException.class)
    public void tokenException(HttpServletRequest request, HttpServletResponse response, SignatureException ex) throws IOException {
        outputMessage(response, JSON.toJSONString(ex.getWriter(), SerializerFeature.DisableCircularReferenceDetect));
    }

    @ExceptionHandler
    @ResponseBody
    public void handleException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
        LOGGER.error("API Exception! ", e);
        BaseRespWriter writer = new BaseRespWriter();
        writer.setErrMsg("API Exception!");
        outputMessage(response, JSON.toJSONString(writer));
    }

    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public void bindException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {
        LOGGER.error("Param Exception! ", e);
        BaseRespWriter writer = new BaseRespWriter();
        writer.setErrMsg("Param Exception!");
        outputMessage(response, JSON.toJSONString(writer));
    }

    private void outputMessage(HttpServletResponse response, String errMsg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        ServletOutputStream os = response.getOutputStream();
        os.write(errMsg.getBytes("utf-8"));
    }

}

啦啦啦

posted @ 2017-05-13 13:27  limeOracle  阅读(1579)  评论(0编辑  收藏  举报