我在我的專案中使用了驗證來處理例外,但現在我知道@ControllerAdvice 也用于例外處理,誰能告訴我為什么我使用它,有什么區別以及如何使用它,因為我無法理解從資源。
使用驗證:
@RestController
@RequestMapping("/api")
@Validated
public class UserController {
@Autowired
UserRepository userrepo;
@PostMapping(value="/users")
ResponseEntity<?> create( @Valid @RequestBody User user) {
User addeduser = userrepo.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(addeduser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
使用控制器建議:
@ControllerAdvice
public class GlobalResponseException {
@ExceptionHandler(MyException.class)
public void handleMyException() {}
}
我真正想知道的是它是如何作業的。
uj5u.com熱心網友回復:
@ControllerAdvice 是 @Component 注釋的一種特殊化,它允許在一個全域處理組件中處理整個應用程式中的例外。它可以被看作是由帶有@RequestMapping 和類似注釋的方法拋出的例外的攔截器。你也可以參考這個: https ://medium.com/@jovannypcg/understanding-springs-controlleradvice-cd96a364033f
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517460.html
標籤:爪哇春天例外
下一篇:在PySpark中通過例外
