首页 文章

泽西对异常的响应未按预期工作

提问于
浏览
0

我正在使用我的数据库中的名称和密码验证用户 . 如果用户名或密码不正确,那么我将抛出自定义异常 .

但我没有得到预期的状态代码和响应 .

我是 Jersey 和网络服务的新手 .

这是我创建响应的函数:

public static Response error(int Status_code, String Request_status ,String data, String Response_error){
        ResponseBuilder response = new ResponseBuilder();
        response.Status_code = Status_code;
        response.Request_status = Request_status;
        response.data =data;
        response.Response_error = Response_error;

        return Response.status(Status_code).entity(response).build();
    }

这是我自定义的Exception类代码:

public class InvalidcredentialsException extends WebApplicationException {
     public InvalidcredentialsException(Response response ) {
         super(response);

     }
}

如果我的模型中的AuthenticateUser函数中的凭据错误(用户名和密码),这就是我在代码中抛出此异常的方法 .

throw new InvalidcredentialsException(ResponseBuilder.error(Response.Status.UNAUTHORIZED.getStatusCode(),"success","","invalid credentials"));

当我检查我的API时,我得到204作为响应,但我期待一个带有我提供的参数的JSON .

我已通过以下方式实现了我的API:

@Path("/user")
public class User {

    @POST
    @Path("/login")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces("application/json")
    public void UserAuthentication(UserCredentials user) {


        UserModel userAuthentication = new UserModel();
        userAuthentication.AuthenticateUser(user);


    }
}

我使用以下链接创建Exception并抛出:

JAX-RS / Jersey how to customize error handling?

这是我的身份验证功能:

public void AuthenticateUser(UserCredentials user) {
        Database db = new Database();
        Connection con = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            String username = user.getUsername();
            String password = user.getPassword();


            con = db.getConnection();

            if (con != null) {

                String selectQuery_UserDetails = "SELECT name,password FROM user WHERE name=? AND password = ?";

                preparedStatement = con.prepareStatement(selectQuery_UserDetails);
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, password);
                rs = preparedStatement.executeQuery();

                if (!rs.isBeforeFirst()) {
                   throw new InvalidcredentialsException(ResponseBuilder.error(Response.Status.UNAUTHORIZED.getStatusCode(),"success","","invalid credentials"));

                }

            }}catch (SQLException e) {

        } finally {
            db.closeConnection(con);

        }

        }

谢谢

1 回答

  • 1

    你正在捕捉但没有处理SQLException . 发生错误时,在访问或尝试访问数据库时,将忽略该异常并且不会创建任何错误响应 . 可能数据库无法访问或配置不正确 . 你应该将异常包装成RuntimeException,如javax.ws.rs.InternalServerErrorException或者只是删除catch语句 . 并且您应该在此处或exception mapper中记录错误,以便您能够分析并解决问题 .

    我建议包装异常并将其记录下来:

    }catch(SQLException e){
        logger.log(Level.SEVERE, "db error while authenticate user", e);
        throw new InternalServerErrorException("db error while authenticate user", e);
    }
    

    现在,运行时异常将由默认exception mapper处理,这将生成错误响应 . 记录其他错误 . 在这段代码中我使用 java.util.logging - 如果需要,将其调整为您使用的日志API .

相关问题