spring boot 異常處理
異常處理是一種識(shí)別并響應(yīng)錯(cuò)誤的一致性機(jī)制,異常機(jī)制可以把程序中的異常處理代碼和正常的業(yè)務(wù)邏輯代碼分離,包裝程序的可讀性和健壯性。在spring boot應(yīng)用程序中,能夠捕獲并及時(shí)的響應(yīng)客戶端的錯(cuò)誤操作是一件非常重要的事情。在本章節(jié)中,我將展示如何處理spring boot中的異常。
1. 相關(guān)注解說(shuō)明
在進(jìn)行演示之前,我們先了解一下在spring boot應(yīng)用程序中與異常處理相關(guān)的幾個(gè)注解
注解名稱 | 說(shuō)明 |
---|---|
@controlleradvice | 該標(biāo)簽用于處理全局的異常信息 |
@exceptionhadler | 用于處理特定異常信息,并返回相關(guān)的響應(yīng)到客戶端 |
首先,我們需要使用**@controlleradvice**注解來(lái)定義一個(gè)全局的異常信息處理類,其語(yǔ)法如下:
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 ... } |
接下來(lái),我們需要定義一個(gè)擴(kuò)展了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**注解來(lái)定義一個(gè)處理具體異常信息的方法,其語(yǔ)法如下:
1
2
3
4
|
@exceptionhandler (value = usernotfoundexception. class ) public responseentity<object> exception(usernotfoundexception ex){ return new responseentity<>( "user not found." , httpstatus.not_found); } |
以上工作準(zhǔn)備完成之后,我們可以使用如下的方式來(lái)處理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); } |
接下來(lái)的內(nèi)容當(dāng)中,我將給出完整的示例代碼,使用http get方法請(qǐng)求一個(gè)用戶信息,當(dāng)用戶存儲(chǔ)庫(kù)中沒有相應(yīng)的用戶信息時(shí),返回“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; } |
說(shuō)明:這里只是做了一個(gè)簡(jiǎn)單的擴(kuò)展
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文件中,我們定義了一個(gè)處理用戶不存在異常的方法,
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. 應(yīng)用主類 —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構(gòu)建文件 — 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. 運(yùn)行測(cè)試
接下來(lái),我們將打包運(yùn)行我們的程序,本次教程演示將使用idea來(lái)運(yùn)行程序,運(yùn)行結(jié)果如下圖所示:
然后,啟動(dòng)postman應(yīng)用程序,我們先在地址欄輸入:http://localhost:8080/users/1 ,觀察正常情況下的測(cè)試信息:
postman的測(cè)試結(jié)果顯示,請(qǐng)求狀態(tài)為200,且返回了用戶的詳細(xì)信息。現(xiàn)在,我們更新url為:http://localhost:8080/users/3 ,再次觀察測(cè)試結(jié)果:
此時(shí)的http status為404,且返回了“user not found.”的提示信息。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:https://juejin.im/post/5caddb255188251b2c397731