我正在使用 Spring MVC 开发 REST 服务。我正在尝试使用 @ExceptionHandler 实现异常处理。当REST层抛出异常时,它不会被@ExceptionHandler拦截。我错过了什么吗?
@Service
@Path("/customer")
public class CustomerResource extends BaseResource{
@Autowired
private CustomerDao customerDao;
........
@GET
@Path("/customer/{accountNumber}")
public Response findCustomerByAccountNumber(String accountNumber) throw Exception{
Customer customer=null;
customer=customerDao.find(....);
if(customer==null)
throw new ResourceNotFoundException();
else
..........
}
}
具有异常处理方法的基类
public abstract class BaseResource {
.......
@ExceptionHandler({ResourceNotFoundException.class })
public Response handleException(Exception ex) {
ErrorResource errResource = new ErrorResource();
.....
return Response.status(Response.Status.NOT_FOUND).entity(errResource).build();
}
}
最佳答案
您抛出 ResourceNotFound 但在异常处理程序中指定了 ResourceNotFoundException - 这些似乎是不同的异常。要么抛出 ResourceNotFoundException 而不是 ResourceNotFound,要么将 ResourceNotFound 添加到异常处理程序中。
编辑: 不知道我一开始是怎么错过的:只是注意到你实际上并没有使用 Spring MVC Controller 。 Spring MVC 异常处理程序仅适用于 Spring MVC Controller 处理的请求。它们处理 Controller 处理程序方法主体中发生的异常。您似乎使用其他东西来处理 REST 请求。
关于java - 一旦从 REST 层抛出异常,@ExceptionHandler 就不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19172253/