总体思路
- 使用注解@ControllerAdvice注入统一处理异常的类
- 使用注解@ExceptionHandler注入处理指定异常的方法
- 其他地方入controller throw出异常后,该异常对应的ExceptionHandler注解方法会处理抛出的异常
异常触发流程
SpringBoot工程中抛出异常,异常处理类中对应异常处理方法收到上述触发的异常,然后对该异常进行统一处理。
- 异常类可以自定义处理,也可以使用java.lang中的异常类进行处理。
- SpringBoot自动管理的Bean(@Controller层,@Service层,@Component等)抛出异常,以及自定义工具类抛出的异常,都可以在统一异常处理类中得到捕获。
异常处理类
@ControllerAdvice
public class ProductExceptionController {
@ExceptionHandler(value = ProductNotfoundException.class)
public ResponseEntity<Object> exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found,id: "+exception.getId(), HttpStatus.NOT_FOUND);
}
}
自定义异常类
public class ProductNotfoundException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String id;
public ProductNotfoundException() {}
public ProductNotfoundException(String id) {
this.setId(id);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Controller类
@RestController
@RequestMapping(value = "/api")
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products/", method = RequestMethod.PUT,consumes = "application/json")
public ResponseEntity<Object> updateProduct(@RequestBody Product product) {
String id = product.getId();
if(!productRepo.containsKey(id))throw new ProductNotfoundException(id);
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK);
}
@RequestMapping(value = "/producer",method = RequestMethod.GET)
public Integer producer() {
System.out.print("--------");
return 1;
}
}