springboot异常处理,及自定义异常

1.自定义系统业务异常

java 中关于异常的分类情况是:throwable 是所有异常和错误的基类,下面在分为Error 和 Exception:

简单的异常体系结构如下图所示:
在这里插入图片描述

其中Exception 下又分为 运行期异常 和 非运行期异常

1:关于Error与Exception
Error是程序无法处理的错误,比如OutOfMemoryError、ThreadDeath等。这些异常发生时, Java虚拟机(JVM)一般会选择线程终止。

2:运行时异常和非运行时异常
Exception 不同于Error是程序本身可以处理的异常;并且程序应该尽可能处理这些异常;

运行时异常都是RuntimeException类及其子类异常,如NullPointerException、IndexOutOfBoundsException等,

这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理。这些异常一般是由程序逻辑错误引起的,
程序应该从逻辑角度尽可能避免这类异常的发生。

非运行时异常是RuntimeException以外的异常,类型上都属于Exception类及其子类。
从程序语法角度讲是必须进行处理的异常,如果不处理,程序就不能编译通过。
如IOException、SQLException等以及用户自定义的Exception异常,一般情况下不自定义检查异常。

业务自定义异常:

package com.abc.common.exception;

/**  
 * @Description:异常类 
 * @create:2019年9月19日 下午2:04:28 
 */
public class BizException extends RuntimeException{

	private static final long serialVersionUID = 1L;

	public BizException(String message) {
        super(message);
    }

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

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

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

2.异常处理类

package com.abc.controller.system.error;

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

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

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.abc.common.exception.BizException;
import com.abc.ds.common.JsonResultDS;

/**
 * @Description:异常处理
 * @author:
 * @create:2019年3月20日 下午3:06:37
 */
@ControllerAdvice
public class GlobalExceptionController {
	
	private final Logger logger=LoggerFactory.getLogger(getClass());
	
	 /**
	  * @Description: 拦截捕捉系统自定义异常
	  * @param request
	  * @param response
	  * @param e
	  * @return
	  * @throws IOException
	  * @author:
	  * @update:2019年9月19日 下午2:33:33
	  */
    @ExceptionHandler(BizException.class)
    public ModelAndView handleRRException(HttpServletRequest request, 
    		HttpServletResponse response, BizException e) throws IOException {
    	
    	logger.error(ExceptionUtils.getStackTrace(e));

		ModelAndView mv = new ModelAndView();
		String msg = e.getMessage().replaceAll("\n", "<br/>");
		if (isAjax(request)) {//ajax请求
			JsonResultDS<?> jsonResultDS = JsonResultDS.errorException(msg);
			
			response.setContentType("application/json;charset=UTF-8");
			response.setStatus(500);
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonResultDS));
            writer.flush();
            writer.close();
    	} else {//页面跳转
    		mv.addObject("exception", msg);
    		mv.setViewName("system/error/500");
    	}
		return mv;
    }
	
    /**
     * @Description: 全局异常捕捉处理
     * @param request
     * @param response
     * @param e
     * @return
     * @throws IOException
     * @author:
     * @update:2019年9月19日 下午2:33:50
     */
	@ExceptionHandler(Exception.class)
	public ModelAndView returnErrorPage(HttpServletRequest request, 
    		HttpServletResponse response, Exception e) throws IOException {
		
		logger.error(ExceptionUtils.getStackTrace(e));
		
		ModelAndView mv = new ModelAndView();
		String msg = e.toString().replaceAll("\n", "<br/>");
		if (isAjax(request)) {//ajax请求
			JsonResultDS<?> jsonResultDS = JsonResultDS.errorException("应用程序异常:"+msg);
			
			response.setContentType("application/json;charset=UTF-8");
			response.setStatus(500);
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonResultDS));
            writer.flush();
            writer.close();
    	} else {//页面跳转
    		mv.addObject("exception", msg);
    		mv.setViewName("system/error/500");
    	}
		return mv;
	}
	
	/**
	 * @Description:判断是否是ajax请求
	 * @param httpRequest
	 * @return
	 * @author:
	 * @update:2019年9月16日 下午1:26:16
	 */
	public static boolean isAjax(HttpServletRequest httpRequest) {
		return (httpRequest.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString()));
	}
}

3.404处理

package com.abc.controller.system.error;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Description:错误页处理(404)
 * @author:
 * @create:2019年3月19日 下午2:18:32
 */
@Controller
public class NotFoundExceptionController implements ErrorController{
	private static final String ERROR_PATH = "/error";

	/**
	 * @Description:错误路径uri
	 * @return
	 * @author:
	 * @update:2019年3月20日 下午2:34:31 
	 */
	@Override
	public String getErrorPath() {
		 return ERROR_PATH;
	}
	
	/**
	 * @Description:跳转到错误页面
	 * @return
	 * @author:
	 * @update:2019年3月20日 下午2:37:49
	 */
	@RequestMapping(ERROR_PATH)
    public String error(){
        return "system/error/404";
    }
	
}

4.JsonResult

package com.abc.ds.common;

import com.fasterxml.jackson.annotation.JsonInclude;

/***
 * ajax请求通用返回结果
 *
 */
public class JsonResultDS<T> {
	
	private String message = "success";// 描述信息
	private int status = 0;//0:成功状态码,1:失败状态码
	@JsonInclude(JsonInclude.Include.NON_NULL)
	private T result = null;

	public JsonResultDS() {
	}
	
	public JsonResultDS(int status, String message) {
		this.status = status;
		this.message = message;
	}

	public JsonResultDS(int status, String message,T result) {
		this.status = status;
		this.message = message;
		this.result = result;
	}

	/**
	 * @Description:抛出异常返回结果
	 * @param msg
	 * @return
	 * @author:
	 * @update:2019年9月18日 上午10:27:31
	 */
	public static JsonResultDS errorException(String msg) {
		return new JsonResultDS(1,msg);
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public T getResult() {
		return result;
	}

	public void setResult(T result) {
		this.result = result;
	}
	
}

5.jquery.ajax.js

//发生ajax请求异常时,ajax方法中有error,执行error方法,否则冒泡到此处的error
$.ajaxSetup({
    error:function(xhr,status,error){
    	if(!xhr || xhr.status == 0){
            return;
        }
        switch(xhr.status){
            case 403:
            	bootbox.alert("抱歉!您没有该功能访问权限,请联系管理员。");
                break;
            case 404:
            	bootbox.alert("您访问的资源不存在,请联系管理员。");
                break;
            case 500:
            	if(xhr.responseJSON != null){
            		//bootbox.alert(xhr.responseJSON.status);//状态码 1:失败
            		bootbox.alert(xhr.responseJSON.message);//错误信息
            	} else {
            		bootbox.alert(xhr.responseText);//错误信息
            	}
                break;
        }
    }
});

/*$(function(){ 
    //.ajaxError事件定位到document对象,文档内所有元素发生ajax请求异常,都将冒泡到document对象的ajaxError事件执行处理,
	//ajax方法中有error,先处理error,再冒泡到此处的error
    $(document).ajaxError(
            //所有ajax请求异常的统一处理函数,处理
            function(event,xhr,options,exc ){
            	debugger;
                if(xhr.status == 'undefined'){
                    return;
                }
                switch(xhr.status){
                    case 403:
                        // 未授权异常
                        alert("系统拒绝:您没有访问权限。");
                        break;
                    case 404:
                        alert("您访问的资源不存在。");
                        break;
                    case 500:
                        alert("系统异常:" + xhr.responseJSON.message);
                        break;
                }
            }
    );
});*/ 




6.测试结果说明

1)异常显示方式:
(1)页面跳转的异常,显示错误页面
(2)ajax请求的异常,弹出提示
2)异常提示信息:
(1)不捕捉异常(提示信息:“应用程序异常”+异常信息)
int i = 1/0;//提示信息:应用程序异常:java.lang.ArithmeticException: / by zero
(2)捕捉异常(提示信息:直接显示自定义提示信息)
try {
int i = 1/0;
} catch (Exception e) {
//throw new BizException(“这是系统自定义异常”);//提示信息:这是系统自定义异常
//throw new BizException(“这是系统自定义异常”,e);//提示信息:这是系统自定义异常
throw new BizException(e);//提示信息:java.lang.ArithmeticException: / by zero
}
3)发生ajax请求异常时,ajax方法中有error,执行error方法,不弹出上述提示;
ajax方法中没有error方法,系统统一处理,弹出上述提示

$.ajax({
				type : "POST",
				url : basePath+"/abc.do",
				dataType : 'json',
				cache : false,
				success : function(errInfo) {
					//业务处理
				},
				error: function(xhr) {//error方法
					//bootbox.alert(xhr.responseJSON.status);//状态码 1:失败
		            bootbox.alert(xhr.responseJSON.message);//提示信息
				}

参考原文链接:https://www.cnblogs.com/beppezhang/p/6397416.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值