Spring Boot-Configure global exception capture

Summary directory link: Spring Boot development common technology blog directory

This article just configures a simple global exception capture, if necessary, other exceptions and custom exceptions can be developed according to the actual situation.

web page jump

The project structure is as follows:

MyExceptionHandler.java

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

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyExceptionHandler {

	private static final String MY_ERROR_VIEW = "error";

	@ExceptionHandler(value = Exception.class)
	public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
		e.printStackTrace();

		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e);
		mav.addObject("url", request.getRequestURL());
		mav.setViewName(MY_ERROR_VIEW);
		return mav;
	}

}

error.html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>错误页面</title>
</head>
<body>

	<h1 style="color: red">发生错误:</h1>
	<div th:text="${url}"></div>
	<div th:text="${exception.message}"></div>

</body>
</html>

Exception test class ErrorController.java 

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 异常测试类
 */
@Controller
@RequestMapping(value = "err")
public class ErrorController {

	@RequestMapping(value = "/error")
	String error() {
		int a = 1 / 0;
		return "aaa";
	}

}

Execution effect:

Ajax form

ErrorController.java

@Controller
@RequestMapping(value = "err")
public class ErrorController {
	@RequestMapping(value = "/getAjaxPage")
	String getAjaxPage() {
		return "ajaxpage";
	}
	@RequestMapping(value = "/getAjaxerror")
	@ResponseBody
	Result getAjaxerror() {
		System.out.println(1/0);
		return Result.ok("ok");
	}
}

AjaxExceptionHandler.java (comment out @ControllerAdvice and @ExceptionHandler on MyEcxceptionHandler.java, when using AjaxExceptionHandler.java, comment out @RestControllerAdvice and @ExceptionHandler on MyEcxceptionHandler.java) Note:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.xiangty.common.Result;

@RestControllerAdvice
public class AjaxExceptionHandler {
	@ExceptionHandler(value = Exception.class)
	public Result errorHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws Exception {
		e.printStackTrace();
		return Result.error(e.getMessage());
	}
}

Add JS and ajaxpage.html front-end content

ajaxpage.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>Ajax页面</title>
    <script src="../static/js/jquery-3.3.1.js"></script>
</head>
<body>

<input type="button" value="点击发送ajax请求" onclick="query()"/>
<br>
<div id="context"></div>


<script>
    function query() {
        $.ajax({
            url: "/err/getAjaxerror",
            type: "POST",
            async: false,
            success: function (response) {
            	console.info(response);
                if (response.status == 10000) {
                    $("#context").text("成功");
                } else {
                    $("#context").text("失败,错误信息:"+response.data);
                }
            },
            error: function(response){
            	$("#context").text("失败,错误信息:"+response.data);
            }
        });
    }
</script>

</body>
</html>

Add WebConfig.java (If you don't add it, a 404 exception will be reported when html references js)

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class WebConfig implements WebMvcConfigurer {
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将所有/static/** 访问都映射到classpath:/static/ 目录下
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

 

Click on the page to send an ajax request

Web page jump and Ajax format compatible

CommonExceptionHandler.java replaces the original AjaxExceptionHandler and MyExceptionHandler

CommonExceptionHandler.java, judge whether the content in the request content is in the form of Ajax, and then use the above two modes of path verification.

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

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.xiangty.common.Result;

@RestControllerAdvice
public class CommonExceptionHandler {

	private static final String MY_ERROR_VIEW = "error";

	@ExceptionHandler(value = Exception.class)
	public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
		e.printStackTrace();
		if(request.getHeader("X-Requested-With") != null 
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			// Ajax形式
			return Result.error(e.getMessage());
		} else {
			// web页面跳转
			ModelAndView mav = new ModelAndView();
			mav.addObject("exception", e);
			mav.addObject("url", request.getRequestURL());
			mav.setViewName(MY_ERROR_VIEW);
			return mav;
		}
	}

}

 

Summary directory link: Spring Boot development common technology blog directory

Guess you like

Origin blog.csdn.net/qq_33369215/article/details/90412391