一、前言
springboot框架对异常的处理提供了几种很强大的方法,我们可以通过@controlleradvice和@exceptionhandler注解实现全局异常的处理,也可以通过实现handlerexceptionresolve接口来完成全局异常的处理。
二、全局异常处理方式一
通过@controlleradvice和@exceptionhandler注解实现全局异常拦截,它可以拦截controller层请求方法抛出的异常信息,同时外加@ responsebody注解,可以实现响应类型为json格式。或者直接使用@restcontrolleradvice和@exceptionhandler注解的方式实现响应类型为json格式的数据。
1.添加依赖
<dependency>
<groupid>org.projectlombok</groupid>
<artifactid>lombok</artifactid>
</dependency>2.自定义异常类
package com.example.dataproject.exception;
/**
* @author qx
* @date 2024/8/8
* @des 自定义异常
*/
public class serviceexception extends runtimeexception {
private integer code;
public integer getcode() {
return code;
}
public serviceexception(string message, integer code) {
super(message);
this.code = code;
}
}3.全局异常处理类
包含对自定义异常和空指针异常的处理。
package com.example.dataproject.exception;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.restcontrolleradvice;
import javax.servlet.http.httpservletrequest;
import java.util.hashmap;
import java.util.map;
/**
* @author qx
* @date 2024/8/8
* @des 全局异常处理类
*/
@restcontrolleradvice
@slf4j
public class globalexception {
@exceptionhandler(value = {exception.class})
public map<string, object> exceptionhandler(httpservletrequest request, exception e) {
log.info("未知异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
map<string, object> map = new hashmap<>();
map.put("code", 999);
map.put("message", e.getmessage());
return map;
}
@exceptionhandler(value = {serviceexception.class})
public map<string, object> serviceexceptionhandler(httpservletrequest request, serviceexception e) {
log.info("自定义异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
map<string, object> map = new hashmap<>();
map.put("code", e.getcode());
map.put("message", e.getmessage());
return map;
}
@exceptionhandler(value = {nullpointerexception.class})
public map<string, object> nullpointexceptionhandler(httpservletrequest request, nullpointerexception e) {
log.info("空指针异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
map<string, object> map = new hashmap<>();
map.put("code", 500);
map.put("message", e.getmessage());
return map;
}
}4.创建控制层测试
package com.example.dataproject.controller;
import com.example.dataproject.exception.serviceexception;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
/**
* @author qx
* @date 2024/8/8
* @des 测试
*/
@restcontroller
public class indexcontroller {
@getmapping("/null")
public string testnull() {
string s = null;
//抛出空指针异常 全局异常中的空指针异常处理会捕获到这个异常
if (true) {
throw new nullpointerexception("空指针异常");
}
return "null success";
}
@getmapping("/service")
public string testservice() {
if (true) {
//抛出自定义异常 全局异常中的自定义异常处理会捕获到这个异常
throw new serviceexception("自定义服务异常", 888);
}
return "service success";
}
@getmapping("/exception")
public string testexception() {
if (true) {
throw new runtimeexception("其他异常");
}
return "exception success";
}
}5.启动程序并访问请求进行测试
测试空指针异常

测试自定义服务异常

其他异常

6.404异常特殊处理
默认情况下,@exceptionhandler注解无法捕捉到 404 异常,比如请求一个无效的地址,返回信息如下:

如果想要捕捉到这种异常,可以在application.properties文件中添加如下配置来实现。
# 如果没有找到请求地址,抛异常 spring.mvc.throw-exception-if-no-handler-found=true # 关闭默认的静态资源路径映射 spring.web.resources.add-mappings=false
启动服务,再次发起地址请求,结果如下:

7.自定义异常页面的实现
某些场景下,当发生异常时希望跳转到自定义的异常页面,如何实现呢?
首先,这里基于thymeleaf模板引擎来开发页面,在templates目录下创建一个异常页面error.html。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>错误</title>
</head>
<body>
出错啦,请与管理员联系<br>
错误详情:<span th:text="${message}"></span>
</body>
</html>我们重新修改一下全局异常处理类,让异常返回结果到页面中。
package com.example.dataproject.exception;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.bind.annotation.restcontrolleradvice;
import org.springframework.web.servlet.modelandview;
import javax.servlet.http.httpservletrequest;
import java.util.hashmap;
import java.util.map;
/**
* @author qx
* @date 2024/8/8
* @des 全局异常处理类
*/
@controlleradvice
@slf4j
public class globalexception {
@exceptionhandler(value = {exception.class})
public modelandview exceptionhandler(httpservletrequest request, exception e) {
log.info("未知异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
/* map<string, object> map = new hashmap<>();
map.put("code", 999);
map.put("message", e.getmessage());
return map;*/
modelandview modelandview = new modelandview();
modelandview.setviewname("error");
modelandview.addobject("message", e.getmessage());
return modelandview;
}
@exceptionhandler(value = {serviceexception.class})
@responsebody
public map<string, object> serviceexceptionhandler(httpservletrequest request, serviceexception e) {
log.info("自定义异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
map<string, object> map = new hashmap<>();
map.put("code", e.getcode());
map.put("message", e.getmessage());
return map;
}
@exceptionhandler(value = {nullpointerexception.class})
@responsebody
public map<string, object> nullpointexceptionhandler(httpservletrequest request, nullpointerexception e) {
log.info("空指针异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
map<string, object> map = new hashmap<>();
map.put("code", 500);
map.put("message", e.getmessage());
return map;
}
}我们重新请求刚才不存在的访问时,这个时候跳转到了页面,并在页面中显示了异常的信息。

三、全局异常处理方式二
在 spring boot 中,除了通过@controlleradvice和@exceptionhandler注解实现全局异常处理外,还有一种通过实现handlerexceptionresolver接口来完成全局异常的处理。
具体实现示例如下:
package com.example.dataproject.exception;
import lombok.extern.slf4j.slf4j;
import org.springframework.stereotype.component;
import org.springframework.web.servlet.handlerexceptionresolver;
import org.springframework.web.servlet.modelandview;
import org.springframework.web.servlet.view.json.mappingjackson2jsonview;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
/**
* @author qx
* @date 2024/8/8
* @des 全局异常处理
*/
@component
@slf4j
public class globalexceptionresolver implements handlerexceptionresolver {
@override
public modelandview resolveexception(httpservletrequest request, httpservletresponse response, object handler, exception e) {
log.error("接口请求出现异常,请求地址:{},错误信息:{}", request.getrequesturi(), e.getmessage());
if (e instanceof nullpointerexception) {
// 设置响应类型为json格式
modelandview mv = new modelandview(new mappingjackson2jsonview());
mv.addobject("code", 500);
mv.addobject("msg", e.getmessage());
return mv;
} else {
// 设置响应类型为错误页面
modelandview mv = new modelandview();
mv.addobject("message", e.getmessage());
mv.setviewname("error");
return mv;
}
}
}如果是空指针异常的话会返回json数据格式,如果是其他异常会在页面上显示异常的信息。
其他异常

空指针异常

虽然这种方式能够处理全局异常,但是 spring 官方不推荐使用它;同时实测过程中发现它无法拦截 404 错误,当请求错误地址时,会优先被defaulthandlerexceptionresolver默认异常处理类拦截,自定义的异常处理类无法捕捉。
到此这篇关于springboot优雅捕捉异常的两种方法小结的文章就介绍到这了,更多相关springboot 捕捉异常内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论