【发布时间】:2020-06-23 00:37:48
【问题描述】:
我创建了一个通过 http 请求进行通信的程序。我使用 Postman 发送请求。当我进行注册时,我调用 API 方法。如果此方法抛出一些异常,我会使用“HandlerMapping”来管理它,它会捕获异常并发送关于它的个性化消息。
HandlerMapping 类:
@Provider
public class HandlerMapper implements ExceptionMapper<InputValidationException>{
@Override
public Response toResponse(InputValidationException exception) {
return Response.status(exception.getStatus().getStatusCode(), exception.getMessage()).build();
}
}
InputValidationException:
public class InputValidationException extends Exception{
private String errorMessage;
private Response.Status status;
@JsonbCreator
public InputValidationException (@JsonbProperty("message") String message, @JsonbProperty("status") Response.Status status) {
this.errorMessage = "Invalid param entered: " + message;
this.status = status;
}
.........
}
现在,当它从 API 方法中抛出异常时,它可以正常工作,并按照我的意愿发送客户消息。但是,如果我发送带有错误参数的消息(例如名称为 null),则不会像使用 api 方法那样创建自定义响应错误,而是使用 500 服务器错误创建默认消息。如何制作通用类以个性化的方式处理错误?
客户客户
public class Client {
private String surname;
private String name;
private String city_of_birth;
.... another parameters ....
@JsonbCreator
public Cliente(@JsonbProperty("surname") String surname, @JsonbProperty("name") String name, @JsonbProperty("city_of_birth") String city_of_birth) throws InputValidationException {
paramValidation(surname, name, city_of_birth, ......... );
this.surname= surname;
this.name= name;
this.city_of_birth= city_of_birth;
.... another parameters ....
}
private void paramValidation(String surname, String name, String city_of_birth) throws InputValidationException{
if( surname == null || surname.isBlank() ){
throw new InputValidationException("surname", Response.Status.METHOD_NOT_ALLOWED);
}
.... other parameter controls ....
}
}
API 类
@Path("homeBanking/client/signup")
public class Registration {
private DaoClient daoC = new DaoClient();
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response createClient(Client client) throws InputValidationException {
daoC.insert(client);
return Response.ok().build();
}
}
【问题讨论】:
标签: java api rest httprequest httpresponse