3 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個贊
創(chuàng)建自定義異常類型比使用ServletException. 為了處理異常,您可以使用@ControllerAdvice. 首先創(chuàng)建自定義異常類型:
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
假設(shè)您的控制器和服務(wù)看起來或多或少是這樣的:
@RestController
@RequestMapping("users")
class UserController {
private final UserService userService;
UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
List<String> users() {
return userService.getUsers();
}
}
@Service
class UserService {
List<String> getUsers() {
// ...
throw new UserNotFoundException("User not found");
}
}
你可以處理你UserNotFoundException使用@ControllerAdvice
@ControllerAdvice
class CustomExceptionHandler {
@ExceptionHandler({UserNotFoundException.class})
public ResponseEntity<Object> handleUserNotFoundException(UserNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
}
}

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個贊
我假設(shè)您希望捕獲應(yīng)用程序中發(fā)生的所有異常。Spring-Boot 提供了一個全局異常處理程序來優(yōu)雅地捕獲所有異常并根據(jù)特定的異常返回響應(yīng)。它使您可以靈活地相應(yīng)地更改狀態(tài)代碼、響應(yīng)數(shù)據(jù)和標(biāo)頭。實(shí)現(xiàn)此功能的幾個有用鏈接是 -
1.)區(qū)域
2.) Spring Boot 教程

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個贊
在你的拋出異常@Service是可以的。ServletException不是很有意義。我的建議是創(chuàng)建自己的 Exception 類擴(kuò)展RuntimeException并拋出它。
所以你最終會得到類似的東西:
一個只調(diào)用服務(wù)方法的Controller(這里最好不要有任何邏輯)
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable("id") Long id) {
return userService.getById(id);
}
}
一個Service調(diào)用DAO類的類(擴(kuò)展JPARepository)
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public User getById(Long id) {
return userDAO.findById(id).orElseThrow(() -> new UserNotFoundException("No user with id = " + id + " found."));
}
}
道:
@Repository
public interface UserDAO extends JpaRepository<User, Long> {
}
注意:它返回Optional<Object>非常方便。
最后是你自己的Exception課。
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
注意:@ResponseStatus- 它會在拋出此異常時返回 HTTP 狀態(tài)代碼 404。
恕我直言,這是開發(fā)您的 rest api 的一種非常干凈和好的方法。
還可以在這里查看:How to get spesific error instead of Internal Service Error。我回答了一個問題,提供了您可能會覺得有用的信息
添加回答
舉報(bào)