Java custom exception information

  Usually in the development process, many exceptions will be encountered. For some known reasons for the exception, if you want to return to the browser at this time, you need to customize the exception of the system

1. Spring injects exception handling class

<bean id ="commonExceptionHandler" class = "com..test.common.exception.handler.CommonExceptionHandler">

2. The injected exception handling class mainly rewrites the resolveException method

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.test.common.constant.ERRORConstants;
import com.test.common.constant.GlobalConstants;
import com.test.common.dto.ResultDTO;
import com.test.common.exception.ServiceException;
import com.test.common.exception.SysException;
import com.test.common.util.SpringContextHolder;
import com.test.common.util.StringUtil;


public class CommonExceptionHandler implements HandlerExceptionResolver {
    private static final Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);

    /**
     * @param request parameter
     * @param response parameter
     * @param obj parameter
     * @param e parameter
     * @return modelview
     */
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
            Exception e) {
        ResultDTO result;
        if (e instanceof SysException) {
            result = handleSysException((SysException) e);
        } else if (e instanceof ServiceException) {
            result = handleServiceException((ServiceException) e);
        } else {
            result = handleSysException(new SysException(ERRORConstants.COMMON_SYSTEM_ERROR, e));
        }

        responseOutWithJson(response, result);
        return new ModelAndView();
    }
private ResultDTO handleSysException(SysException ex) { ResultDTO result = new ResultDTO(); result.setCode(ex.getCode()); if(StringUtil.isNotEmpty(ex.getMsg())){ result.setMessage(ex.getMsg());//Here is the information set by yourself }else { result.setMessage(SpringContextHolder.getMessage(ex.getCode(), null)); } LOG.error(new StringBuilder().append(result.getCode()).append(result.getMessage()).toString(), ex); return result; } private ResultDTO handleServiceException(ServiceException ex) { ResultDTO result = new ResultDTO(); result.setCode(ex.getCode()); result.setMessage(SpringContextHolder.getMessage(ex.getCode(), null)); LOG.error(new StringBuilder().append(result.getCode()).append(result.getMessage()).toString()); return result; } protected void responseOutWithJson(HttpServletResponse response, Object responseObject) { JSONObject responseJSONObject = JSONObject.fromObject(responseObject); String jsonString = responseJSONObject.toString(); response.setCharacterEncoding(GlobalConstants.DEFAULT_ENCODING); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.append(jsonString); LOG.debug("Return is\n"); LOG.debug(jsonString); } catch (IOException e) { LOG.debug("Error responseOutWithJson"); } finally { if (out != null) { out.close(); } } } }

 3. Custom system exception class

package com.test.common.exception.base;
 
public  class BaseCommonException extends RuntimeException {
     private  static  final  long serialVersionUID = 1L ;
     private String code;
     private String msg;//For storing exception information

    /**
     * Constructor
     */
    public BaseCommonException() {
        super();
    }

    /**
     *
     * @param cause 参数
     */
    public BaseCommonException(Throwable cause) {
        super(cause);
    }
    
    /**
     *
     * @param code 参数
     */
    public BaseCommonException(String code) {
        this.setCode(code);
    }

    /**
     *
     * @param code parameter
     * @param e 参数
     */
    public BaseCommonException(String code, Throwable e) {
        super(e);
        this.setCode(code);
    }
    
    /**
     *
     * @param code parameter
     * @param e 参数
     */
    public BaseCommonException(String code, Throwable e,String msg) {
        super(e);
        this.setCode(code);
        this.setMsg(msg);
    }

    /**
     *
     * @return code
     */
    public String getCode() {
        return code;
    }

    /**
     *
     * @param code 参数
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     *
     * @return msg
     */
    public String getMsg() {
        return msg;
    }

    /**
     *
     * @param msg 参数
     */
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}

4. Service class

    public boolean test() {
        String msg = "";
        try {
                        msg = "custom information" ;
             return  true ;
        } catch (Exception e) {
             throw  new BaseCommonException("300",e,
                     "Failure message: "+ msg);
        }
    }    

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324962746&siteId=291194637