com.fengduo.bee.commons.exception.SystemExceptionResolver.java Source code

Java tutorial

Introduction

Here is the source code for com.fengduo.bee.commons.exception.SystemExceptionResolver.java

Source

/*
 * Copyright 2015-2020 Fengduo.com All right reserved. This software is the confidential and proprietary information of
 * Fengduo.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with Fengduo.com.
 */
package com.fengduo.bee.commons.exception;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

/**
 * ?
 * 
 * @author zxc May 28, 2015 11:18:31 PM
 */
public class SystemExceptionResolver extends AbstractHandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {
        if (ex instanceof MaxUploadSizeExceededException) {// ?
            long fileSize = ((MaxUploadSizeExceededException) ex).getMaxUploadSize();
            String error = "??,?".concat("" + fileSize / (1024)).concat("KB");
            String message = "{\"status\":\"0\",\"msg\":\"".concat(error).concat("\"}");
            response.setContentType("text/html;charset=UTF-8");
            setResponse(response, -1, message);
            return new ModelAndView();
        } else {
            logger.info(
                    "\n----------------------------------------\nsome error happen\n----------------------------------------");
            ex.printStackTrace();
            return new ModelAndView("error");
        }
    }

    /**
     * Response?
     * 
     * @param response
     * @param errorCode
     * @param errorMsg
     */
    private void setResponse(HttpServletResponse response, int errorCode, String errorMsg) {
        if (-1 != errorCode)
            response.setStatus(errorCode);
        if (errorMsg != null)
            printJSON(response, errorMsg);
    }

    /**
     * Response  responseText
     * 
     * @param response
     * @param errorMsg
     */
    private void printJSON(HttpServletResponse response, String errorMsg) {
        response.setCharacterEncoding("UTF-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(errorMsg);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}