0

我正在使用 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();
}

}
4

1 回答 1

2

You are throwing ResourceNotFound but have specified ResourceNotFoundException in the exception handler - these seem to be different exceptions. Either throw ResourceNotFoundException instead of ResourceNotFound or add ResourceNotFound to the exception handler.

EDIT: Don't know how I missed it at first: just noticed you don't actually use Spring MVC controller. Spring MVC exception handlers only work for requests handled by Spring MVC controllers. They handle exceptions that happen in the body of controller handler methods. You seem to use something else to handle REST requests.

于 2013-10-04T17:54:23.717 回答