栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java自定义异常并处理异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java自定义异常并处理异常

自定义异常:
@Data
public final class MyException extends RuntimeException
{
    private Integer status = ExceptionCode.SERVICEEXCEPTION.getCode();


    public MyException() {

    }

    public MyException(ExceptionCode status,String message) {

        super(status.getCode()+"&"+message);
        this.status = status.getCode();
    }


    public MyException(Throwable cause) {
        super(cause);
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }

    public MyException(String message, Throwable cause,
                       boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

}
public enum ExceptionCode
{
    TOKENEXCEPTION(40000),//登录TOKEN异常
    SERVICEEXCEPTION(41000),//业务异常(包括参数)
    AUTHEXCEPTION(42000);//权限异常

    private final Integer code;


    ExceptionCode(Integer code)
    {
        this.code = code;

    }
    public Integer getCode()
    {
        return code;
    }

}

自定义异常处理:
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

	@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
	public void handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		//返回给前端的信息
		Map map = new HashMap();
		String message = ex.getMessage();
		Integer status = 500;

		if(ex.getClass().equals(MyException.class)){
			//是自定义异常
			String[] str = message.split("&");
			status = MyUtil.convertToInt(str[0], 500);
			message = str[1];
		}else{
			message = "系统错误";
		}

		if (status.equals(500)) {
			System.out.println("非业务异常,请查看错误日志");
			log.error(MyExceptionUtil.getExceptionAllinformation(ex));
		} else {
			System.out.println("错误" + status + ":" + message);
		}

		map.put("status", status);
		map.put("message", message);
		request.setAttribute("errorMap", map);
		response.setHeader("Content-Type", "application/json");
		response.setStatus(403);
		MyUtil.writeObjectToClient(map, response);
	}
}
  
    public static void writeObjectToClient(Object obj, HttpServletResponse response) {

        String jsonStr = JSON.toJSONString(obj);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().print(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  
    public static String getExceptionAllinformation(Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        e.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return ret;
    }
结束:

这样只要

throw new MyException(ExceptionCode.SERVICEEXCEPTION,"");

就能返回异常信息给前端了,前端就能统一进行异常处理了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/940314.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号