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

网友投稿 372 2023-01-08


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

Spring Boot 异常处理

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

1. 相关注解说明

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

注解名称

说明

@ControllerAdvice

该标签用于处理全局的异常信息

@ExcsuIgzOwHeptionHadler

用于处理特定异常信息,并返回相关的响应到客户端

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

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类的自定义异常处理类:

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**注解来定义一个处理具体异常信息的方法,其语法如下:

@ExceptionHandler(value = UserNotFoundException.class)

public ResponseEntity exception(UserNotFoundException ex){

return new ResponseEntity<>("user not found.", HttpStatus.NOT_FOUND);

}

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

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

public ResponseEntity 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

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

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 {

@Exceptihttp://onHandler(value = UserNotFoundException.class)

public ResponseEntity exception(UserNotFoundException ex){

return new ResponseEntity<>("user not found.", HttpStatus.NOT_FOUND);

}

}

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

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 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 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

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(ExceptionHandlerApplicatsuIgzOwHion.class, args);

}

}

5. 用户POJO类 —suIgzOwH 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构建文件 — pom.xml

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.3.RELEASE

com.ramosteasuIgzOwHr

exception-handler

0.0.1-SNAPSHOT

exception-handler

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.projectlombok

lombok

org.springframework.boot

spring-boot-maven-plugin

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.3.RELEASE

com.ramosteasuIgzOwHr

exception-handler

0.0.1-SNAPSHOT

exception-handler

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.projectlombok

lombok

org.springframework.boot

spring-boot-maven-plugin

8. 运行测试

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

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

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

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

总结

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微服务网关验证jwt(微服务网关如何调用服务)
下一篇:springboot 事件监听的实现方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~