Bean Validation是验证对象的好选择,但是如何在ConstraintViolationException抛出时自定义REST API的响应(使用RESTeasy)?
例如:
@POST
@Path("company")
@Consumes("application/json")
public void saveCompany(@Valid Company company) {
...
}
Run Code Online (Sandbox Code Playgroud)
包含无效数据的请求将返回400具有以下正文的HTTP 状态代码:
[PARAMETER]
[saveCompany.arg0.name]
[{company.name.size}]
[a]
Run Code Online (Sandbox Code Playgroud)
这很好但不够,我想在JSON文档中规范化这些错误.
我该如何自定义此行为?
我在Wildfly 8.2.0中使用Bean验证和RestEasy.最后:
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
public class UserEndpoint
{
//more code
@GET
@Path("/encrypt/{email}")
public Response fetchEncryptedId(@PathParam("email") @NotNull String email)
{
String encryptedUserId = userService.getEncryptedUserId(email);
return Response.ok().entity(new UserBo(encryptedUserId)).build();
}
}
Run Code Online (Sandbox Code Playgroud)
这基本上有效.现在我想把响应作为JSON对象,但我不能让它工作.我的所有"应用程序"异常都由我的异常映射器处理,这有效:
@Provider
public class DefaultExceptionMapper implements ExceptionMapper<Exception>
{
private static final String MEDIA_TYPE = "application/json";
private LoggingService loggingService;
@EJB
public void setLoggingService(LoggingService loggingService)
{
this.loggingService = loggingService;
}
@Override
public Response toResponse(Exception exception)
{
ResponseObject responseObject = new ResponseObject();
responseObject.registerExceptionMessage(exception.getMessage());
if (exception instanceof ForbiddenException)
{
loggingService.log(LogLevel.ERROR, ((ForbiddenException)exception).getUserId(), ExceptionToStringMapper.map(exception));
return Response.status(Status.FORBIDDEN).type(MEDIA_TYPE).entity(responseObject).build();
}
//more …Run Code Online (Sandbox Code Playgroud)