我有帐户的REST服务。控制器调用服务层以查找帐户。 AccountService可以抛出域异常。它通常是与客户端输入错误相关的情况。在这种情况下,我想用ClientException包装域异常。有没有办法可以向客户端显示状态代码400和异常消息?或者是否更好地处理服务层检测到非法参数的情况?
@Controller
class AccountController
@ResponseBody
@RequestMapping("/accounts/${accountId}")
public Account account(@PathVariable int accountId, HttpServletResponse response){
try{
return accountService.find("Account not found with id: " + accountId);
}catch(Exception e){
response.setStatus(400);
throw new ClientException(e);
}
}
}
class AccountService{
public Account find(int accountId){
if(acountId > 100){
throw new AccountNotFoundException(accountId);
}else{
return new Account(accountId, "someone");
}
}
}
答案 0 :(得分:0)
如果这是一个REST服务,那么只需设置响应状态和JSON正文(带有错误消息)即可。没有必要抛出ClientException。
答案 1 :(得分:0)
您可以创建一个异常处理程序来获取异常并将其编组为JSON响应对象。
我之前做过这个,它运行良好,但我知道更长的源代码要分享。 。
以Spring MVC的异常处理程序为出发点。