相关疑难解决方法(0)

Bean验证引发ConstraintViolationException时自定义JAX-RS响应

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文档中规范化这些错误.

我该如何自定义此行为?

java rest jax-rs resteasy bean-validation

6
推荐指数
1
解决办法
3341
查看次数

Wildfly:ExceptionMapper不是通过RestEasy JSR-303 Bean验证触发的

我在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)

json resteasy bean-validation wildfly wildfly-8

4
推荐指数
1
解决办法
1988
查看次数

标签 统计

bean-validation ×2

resteasy ×2

java ×1

jax-rs ×1

json ×1

rest ×1

wildfly ×1

wildfly-8 ×1