首页 文章

Jersey / JAX-RS ExceptionMapper MySQL

提问于
浏览
2

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

我有一个UserFacade类,AbstractFacade类和User类本身,都非常标准,主要是通过在Netbeans中创建一个带有Database的新Web Service RestFUL项目生成的 . 我的问题是,我现在想开始捕获错误,说“唯一约束违规”错误 . 我以为我需要实现一个异常映射器...我的外观中有以下内容:

@Provider
    public class EntityNotFoundMapper implements ExceptionMapper {

        @Override
        public javax.ws.rs.core.Response toResponse(PersistenceException ex) {
            return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
        }
    }

这是我得到的错误,不是我的自定义异常处理程序捕获的 .

WARNING:   StandardWrapperValve[service.ApplicationConfig]: Servlet.service() for servlet service.ApplicationConfig threw exception
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'usernamegoeshere' for key 'username'

我觉得我很接近,唯一的原因是我没有尝试从上面的例子中捕获MySQLIntegrityConstraintViolationException,因为我只是试图 grab 每个可能的错误FIRST(以确保其工作),然后我会缩小并且在我看到语法正常工作之后具体 .

我究竟做错了什么?

1 回答

  • 3
    • 始终参数化 ExceptionMapper
    public class EntityNotFoundMapper
        implements ExceptionMapper<PersistenceException> { ... }
    
    @Provider
    public class MySqlIntegrityMapper
        implements ExceptionMapper<MySQLIntegrityConstraintViolationException> {
    
        @Override
        public Response toResponse(MySQLIntegrityConstraintViolationException ex) {
            return ...;
        }
    }
    

    或者更通用SQLException(因为 MySQLIntegrityConstraintViolationException 继承自它):

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

相关问题