如何优雅的处理Spring Boot异常信息详解

2025-05-29 0 85

spring boot 异常处理

异常处理是一种识别并响应错误的一致性机制,异常机制可以把程序中的异常处理代码和正常的业务逻辑代码分离,包装程序的可读性和健壮性。在spring boot应用程序中,能够捕获并及时的响应客户端的错误操作是一件非常重要的事情。在本章节中,我将展示如何处理spring boot中的异常

1. 相关注解说明

在进行演示之前,我们先了解一下在spring boot应用程序中与异常处理相关的几个注解

注解名称 说明
@controlleradvice 该标签用于处理全局的异常信息
@exceptionhadler 用于处理特定异常信息,并返回相关的响应到客户端

首先,我们需要使用**@controlleradvice**注解来定义一个全局的异常信息处理类,其语法如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
package com.ramostear.exception.handler;

import org.springframework.http.httpstatus;

import org.springframework.http.responseentity;

import org.springframework.web.bind.annotation.controlleradvice;

import org.springframework.web.bind.annotation.exceptionhandler;

/**

* @author : ramostear

* @date : 2019/3/6 0006-16:33

*/

@controlleradvice

public class userexceptionhandler {

//todo ...

}

接下来,我们需要定义一个扩展了runtimeexception类的自定义异常处理类:

?

1

2

3

4

5

6

7

8

9
package com.ramostear.exception.handler;

/**

* @author : ramostear

* @date : 2019/3/6 0006-16:31

*/

public class usernotfoundexception extends runtimeexception{

private static final long serialversionuid = 5534028121297403043l;

}

最后,我们使用**@exceptionhandler**注解来定义一个处理具体异常信息的方法,其语法如下:

?

1

2

3

4
@exceptionhandler(value = usernotfoundexception.class)

public responseentity<object> exception(usernotfoundexception ex){

return new responseentity<>("user not found.", httpstatus.not_found);

}

以上工作准备完成之后,我们可以使用如下的方式来处理api中的异常信息:

?

1

2

3

4

5

6

7
@getmapping("/users/{id}")

public responseentity<object> getuser(@pathvariable(name = "id") long id){

if(!userrepo.containskey ( id )){

throw new usernotfoundexception ();

}

return new responseentity<> (userrepo.get (id), httpstatus.ok);

}

接下来的内容当中,我将给出完整的示例代码,使用http get方法请求一个用户信息,当用户存储库中没有相应的用户信息时,返回“user not found”提示信息。

2. 自定义异常信息类 — usernotfoundexception.java

?

1

2

3

4

5

6

7

8

9
package com.ramostear.exception.handler;

/**

* @author : ramostear

* @date : 2019/3/6 0006-16:31

*/

public class usernotfoundexception extends runtimeexception{

private static final long serialversionuid = 5534028121297403043l;

}

说明:这里只是做了一个简单的扩展

2. 全局异常处理类 —userexceptionhandler.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
package com.ramostear.exception.handler;

import org.springframework.http.httpstatus;

import org.springframework.http.responseentity;

import org.springframework.web.bind.annotation.controlleradvice;

import org.springframework.web.bind.annotation.exceptionhandler;

/**

* @author : ramostear

* @date : 2019/3/6 0006-16:33

*/

@controlleradvice

public class userexceptionhandler {

@exceptionhandler(value = usernotfoundexception.class)

public responseentity<object> exception(usernotfoundexception ex){

return new responseentity<>("user not found.", httpstatus.not_found);

}

}

在userexceptionhandler.java文件中,我们定义了一个处理用户不存在异常的方法,

3. api类 — userservicecontroller.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41
package com.ramostear.exception.handler.controller;

import com.ramostear.exception.handler.usernotfoundexception;

import com.ramostear.exception.handler.model.user;

import org.springframework.http.httpstatus;

import org.springframework.http.responseentity;

import org.springframework.web.bind.annotation.getmapping;

import org.springframework.web.bind.annotation.pathvariable;

import org.springframework.web.bind.annotation.restcontroller;

import javax.annotation.postconstruct;

import java.util.hashmap;

import java.util.map;

/**

* @author : ramostear

* @date : 2019/3/6 0006-16:26

*/

@restcontroller

public class userservicecontroller {

private static map<long,user> userrepo = new hashmap<>();

@postconstruct

public void inituserrepo(){

user admin = new user ().setid ( 1 ).setname ( "admin" );

userrepo.put ( admin.getid (),admin );

user editor = new user ().setid ( 2 ).setname ( "editor" );

userrepo.put ( editor.getid (),editor );

}

@getmapping("/users/{id}")

public responseentity<object> getuser(@pathvariable(name = "id") long id){

if(!userrepo.containskey ( id )){

throw new usernotfoundexception ();

}

return new responseentity<> (userrepo.get (id), httpstatus.ok);

}

}

在getuser()方法中,如果用户没有找到,则抛出usernotfoundexception异常

4. 应用主类 —exceptionhandlerapplication.java

?

1

2

3

4

5

6

7

8

9

10

11

12
package com.ramostear.exception.handler;

import org.springframework.boot.springapplication;

import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication

public class exceptionhandlerapplication {

public static void main(string[] args) {

springapplication.run(exceptionhandlerapplication.class, args);

}

}

5. 用户pojo类 — user.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29
package com.ramostear.exception.handler.model;

import lombok.getter;

import lombok.noargsconstructor;

import lombok.setter;

/**

* @author : ramostear

* @date : 2019/3/6 0006-16:23

*/

@getter

@setter

@noargsconstructor

public class user {

private long id;

private string name;

public user setid(long id){

this.id = id;

return this;

}

public user setname(string name){

this.name = name;

return this;

}

}

6. maven构建文件 — pom.xml

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47
<?xml version="1.0" encoding="utf-8"?>

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"

xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelversion>4.0.0</modelversion>

<parent>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-parent</artifactid>

<version>2.1.3.release</version>

<relativepath/> <!-- lookup parent from repository -->

</parent>

<groupid>com.ramostear</groupid>

<artifactid>exception-handler</artifactid>

<version>0.0.1-snapshot</version>

<name>exception-handler</name>

<description>demo project for spring boot</description>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-web</artifactid>

</dependency>

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-test</artifactid>

<scope>test</scope>

</dependency>

<dependency>

<groupid>org.projectlombok</groupid>

<artifactid>lombok</artifactid>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-maven-plugin</artifactid>

</plugin>

</plugins>

</build>

</project>

8. 运行测试

接下来,我们将打包运行我们的程序,本次教程演示将使用idea来运行程序,运行结果如下图所示:

如何优雅的处理Spring Boot异常信息详解

然后,启动postman应用程序,我们先在地址栏输入:http://localhost:8080/users/1 ,观察正常情况下的测试信息:

如何优雅的处理Spring Boot异常信息详解

postman的测试结果显示,请求状态为200,且返回了用户的详细信息。现在,我们更新url为:http://localhost:8080/users/3 ,再次观察测试结果:

如何优雅的处理Spring Boot异常信息详解

此时的http status为404,且返回了“user not found.”的提示信息。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。

原文链接:https://juejin.im/post/5caddb255188251b2c397731

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 如何优雅的处理Spring Boot异常信息详解 https://www.kuaiidc.com/109185.html

相关文章

发表评论
暂无评论