【问题标题】:Jersey / JAX-RS ExceptionMapper MySQLJersey / JAX-RS ExceptionMapper MySQL
【发布时间】:2014-01-24 04:56:00
【问题描述】:

我正在学习 Jersey / JAX-RS,我需要一些关于 ExceptionMapper 的帮助。

我有一个 UserFacade 类、AbstractFacade 类和 User 类本身,它们都非常标准,主要是通过在 Netbeans 中使用数据库创建一个新的 Web 服务 RestFUL 项目而生成的。我的问题是,我现在想开始捕捉错误,比如“唯一约束违反”错误。我认为我需要实现一个异常映射器......我的外观中有以下内容:

@Provider 公共类 EntityNotFoundMapper 实现 ExceptionMapper { @覆盖 公共 javax.ws.rs.core.Response toResponse(PersistenceException ex) { return Response.status(404).entity(ex.getMessage()).type("text/plain").build(); } }

这是我得到的错误,没有被我的自定义异常处理程序捕获。

警告:StandardWrapperValve[service.ApplicationConfig]: Servlet.service() for servlet service.ApplicationConfig 抛出异常 com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目“用户名goeshere”键“用户名”

我觉得我已经接近了,我没有尝试从上面的示例中捕获 MySQLIntegrityConstraintViolationException 的唯一原因是因为我只是想首先捕获所有可能的错误(以确保其正常工作),然后我'在我看到语法正常工作后会缩小并具体化。

我做错了什么?

【问题讨论】:

    标签: java web-services rest jersey jax-rs


    【解决方案1】:
    1. 总是参数化ExceptionMapper:

      public class EntityNotFoundMapper
          implements ExceptionMapper<PersistenceException> { ... }
      
    2. MySQLIntegrityConstraintViolationException 似乎没有扩展PersistenceException。要捕获MySQLIntegrityConstraintViolationException,您需要直接为此类或其前身之一创建ExceptionMapper,例如:

      @Provider
      public class MySqlIntegrityMapper
          implements ExceptionMapper<MySQLIntegrityConstraintViolationException> {
      
          @Override
          public Response toResponse(MySQLIntegrityConstraintViolationException ex) {
              return ...;
          }
      }
      

      或者更通用的SQLExceptionMySQLIntegrityConstraintViolationException 继承自它):

      @Provider
      public class SqlExceptionMapper implements ExceptionMapper<SQLException> {
      
          @Override
          public Response toResponse(SQLException ex) {
              return ...;
          }
      }
      

    【讨论】:

    • 你知道我在哪里可以找到如何做你答案的第 2 部分的例子吗?
    • 非常感谢您迄今为止的帮助,我觉得我快到了。现在我收到以下错误:WARNING: The following warnings have been detected: WARNING: HK2 service reification failed for [service.UserFacadeREST$SqlExceptionMapper] with an exception: MultiException stack 1 of 2 java.lang.NoSuchMethodException: Cannot instantiate service.UserFacadeREST$SqlExceptionMapper class. Instantiation of non-static member classes is not supported.
    • 您的SqlExceptionMapperUserFacadeREST 中的内部类。将SqlExceptionMapper 设为静态(public static class SqlExceptionMapper implements ExceptionMapper&lt;SQLException&gt; { ... }),甚至更好地将其设为UserFacadeREST 之外的常规类。
    • 谢谢您,先生,我希望能给您买杯咖啡或苏打水之类的:)
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2016-12-02
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多