处理API中的异常和错误并向客户端发送正确的响应对企业应用程序有利。在这个章节,我们将学到怎么处理Spring Boot的异常。
在我们开始进行异常处理之前,让我们了解一下接下来的注解。
Controller Advice
使用@ControllerAdvie是一个增强功能注解用来处理全局异常。
Exception Handler
使用@ExceptionHandler注解来处理指定的异常以及发送自定义的客户端响应。
- 定义一个继承RuntimeException类的自定义异常类
- 定义一个异常最强功能,即使用@ControllerAdvie注解标注一个类
- 定义一个@ExceptionHandler注解标注的方法来处理上面的异常类。
- 最后就可以在API中抛出指定异常后会及时给客户端发送’错误’响应
案例如下:
自定义Exception类
1
2
3
4package com.restfulapio.demo.exception;
public class ProductException extends RuntimeException {
private static final long serialVersionUID = -5887391132719068065L;
}自定义异常处理增强
1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.restfulapio.demo.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
public class ProductExceptionController {
(value = ProductException.class)
public ResponseEntity<Object> exception(){
return new ResponseEntity<>("product not found", HttpStatus.NOT_FOUND);
}
}API添加异常抛出
1
2
3
4
5
6
7
8(value = "/products/{id}",method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id,@RequestBody Product product){
if (!productRepo.containsKey(id)) throw new ProductException();
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successfully",HttpStatus.OK);
}
测试URL: PUT : http://localhost:8080/products/3
评论加载中