欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何優(yōu)雅的處理Spring Boot異常信息詳解

 更新時(shí)間:2019年04月13日 07:14:27   作者:羅摩爾  
這篇文章主要給大家介紹了關(guān)于如何優(yōu)雅的處理Spring Boot異常信息的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

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ǔ)法如下:

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類的自定義異常處理類:

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ǔ)法如下:

@ExceptionHandler(value = UserNotFoundException.class)
 public ResponseEntity<Object> exception(UserNotFoundException ex){
  return new ResponseEntity<>("user not found.", HttpStatus.NOT_FOUND);
 }

以上工作準(zhǔn)備完成之后,我們可以使用如下的方式來(lái)處理API中的異常信息:

@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ù)中沒(méi)有相應(yīng)的用戶信息時(shí),返回“user not found”提示信息。

2. 自定義異常信息類 — UserNotFoundException.java

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

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

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()方法中,如果用戶沒(méi)有找到,則拋出UserNotFoundException異常。

4. 應(yīng)用主類 —ExceptionHandlerApplication.java

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

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

<?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ì)腳本之家的支持。

相關(guān)文章

  • Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式

    Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式

    本文主要介紹了Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式,主要包括了Thread.sleep()方法,.sleep()使用Timer類或使用ScheduledExecutorService接口,感興趣的可以了解一下
    2023-12-12
  • Java Socket編程實(shí)例(五)- NIO UDP實(shí)踐

    Java Socket編程實(shí)例(五)- NIO UDP實(shí)踐

    這篇文章主要講解Java Socket編程中NIO UDP的實(shí)例,希望能給大家做一個(gè)參考。
    2016-06-06
  • Java多線程 CompletionService

    Java多線程 CompletionService

    這篇文章主要介紹了Java多線程 CompletionService,CompletionService用于提交一組Callable任務(wù),其take方法返回已完成的一個(gè)Callable任務(wù)對(duì)應(yīng)的Future對(duì)象,需要的朋友可以參考一下文章詳細(xì)內(nèi)容
    2021-10-10
  • java 序列化與反序列化的實(shí)例詳解

    java 序列化與反序列化的實(shí)例詳解

    這篇文章主要介紹了java 序列化與反序列化的實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • Mybatis-plus如何開啟二級(jí)緩存

    Mybatis-plus如何開啟二級(jí)緩存

    這篇文章主要介紹了Mybatis-plus如何開啟二級(jí)緩存問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Spring\SpringBoot配置連接數(shù)據(jù)庫(kù)的方法

    Spring\SpringBoot配置連接數(shù)據(jù)庫(kù)的方法

    最近在學(xué)習(xí)SpringBoot,第一步就是要配置數(shù)據(jù)庫(kù),本文詳細(xì)的介紹了Spring\SpringBoot配置連接數(shù)據(jù)庫(kù)的方法,有需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-06-06
  • 帶你快速搞定java多線程(3)

    帶你快速搞定java多線程(3)

    這篇文章主要介紹了java多線程編程實(shí)例,分享了幾則多線程的實(shí)例代碼,具有一定參考價(jià)值,加深多線程編程的理解還是很有幫助的,需要的朋友可以參考下
    2021-07-07
  • SpringBoot中@Import注解的使用方式

    SpringBoot中@Import注解的使用方式

    這篇文章主要介紹了SpringBoot中@Import注解的使用方式,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-05-05
  • java調(diào)用c程序通信示例代碼

    java調(diào)用c程序通信示例代碼

    這篇文章主要介紹了java調(diào)用c程序通信示例,大家參考使用吧
    2013-12-12
  • java實(shí)現(xiàn)/創(chuàng)建線程的幾種方式小結(jié)

    java實(shí)現(xiàn)/創(chuàng)建線程的幾種方式小結(jié)

    在JAVA中,用Thread類代表線程,所有線程對(duì)象都必須是Thread類或者Thread類子類的實(shí)例,下面這篇文章主要介紹了java實(shí)現(xiàn)/創(chuàng)建線程的幾種方式,需要的朋友可以參考下
    2021-08-08

最新評(píng)論