Java自定义异常信息

Posted freeLife

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java自定义异常信息相关的知识,希望对你有一定的参考价值。

  通常在开发过程中,会遇到很多异常,对于一些知道异常的原因,这时候想要返回给浏览器,就需要自定义系统的异常

1、Spring  注入异常处理类

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

2、注入的异常处理类,主要是重写resolveException方法

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 参数
     * @param response 参数
     * @param obj 参数
     * @param e 参数
     * @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());//这里获取的是自己设置的信息 }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("返回是\n"); LOG.debug(jsonString); } catch (IOException e) { LOG.debug("Error responseOutWithJson"); } finally { if (out != null) { out.close(); } } } }

 3、自定义系统异常类

package com.test.common.exception.base;

public class BaseCommonException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    private String code;
    private String msg;//用于存放异常信息

    /**
     * 构造函数
     */
    public BaseCommonException() {
        super();
    }

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

    /**
     * 
     * @param code 参数
     * @param e 参数
     */
    public BaseCommonException(String code, Throwable e) {
        super(e);
        this.setCode(code);
    }
    
    /**
     * 
     * @param code 参数
     * @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类

    public boolean test() {
        String msg = "";
        try {
                        msg = "自定义信息";
            return true;
        } catch (Exception e) {
            throw new BaseCommonException("300",e,
                    "失败信息:"+msg);
        }
    }    

 


以上是关于Java自定义异常信息的主要内容,如果未能解决你的问题,请参考以下文章

00086_自定义异常

VSCode创建自定义用户片段

Java try-catch自定义捕捉异常

Java中的自定义异常捕获方式

零基础学Java—自定义异常(四十八)

Java:如何获取错误信息?