我已经实现了以下通用ExceptionMapper:
@Provider
@JBossLog
public class RestExceptionMapper implements ExceptionMapper<Throwable> {
@Context
HttpServerRequest request;
@Context
SecurityContext securityContext;
@Context
UriInfo uriInfo;
@Override
public Response toResponse(Throwable exception) {
final Throwable rootCause = ExceptionUtils.getRootCause(exception);
log.errorf("General exception: %s", rootCause.getMessage(), rootCause);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
我已经实现了以下 REST 资源:
@Path("/process-settings")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ProcessSettingResource {
@POST
@RunOnVirtualThread
public RestResponse<Object> createProcessSetting(
@Valid CreateProcessSettingDto processSettingDto,
@Context UriInfo uriInfo
) {
URI location = uriInfo.getAbsolutePathBuilder()
.path(String.valueOf(1L))
.build();
if (processSettingDto.getProcessInfo().getProcessName().equals("FAIL")) {
// ResteasyReactiveViolationException is NOT handled by RestExceptionMapper
throw new ResteasyReactiveViolationException("Process Name is invalid", new HashSet<>());
// RuntimeException IS handled by RestExceptionMapper
// throw new RuntimeException("Process Name is invalid");
// IllegalArgumentException IS handled by RestExceptionMapper
// throw new IllegalArgumentException("Process Name is invalid");
}
return ResponseBuilder.create(Status.CREATED).location(location).build();
}
}
有人可以解释一下为什么某些异常不由通用 ExceptionMapper (如
ResteasyReactiveViolationException
或其超类 ConstraintViolationException
)处理,而其中一些异常由通用 ExceptionMapper (如 RuntimeException
、IllegalArgumentException
)处理。
有人可以解释一下这是一个错误还是一个功能吗?
如果是一个功能你能告诉我这些规则写在哪里吗?
当 RESTEasy 遇到 ResteasyReactiveViolationException 类型的异常时,它会在内部处理它们,而不传递给通用 ExceptionMapper。
所以我认为对于上述场景,我们需要创建一个特定于 ResteasyReactiveViolationException 的自定义异常映射器
@Provider
public class ResteasyReactiveViolationExceptionMapper implements ExceptionMapper<ResteasyReactiveViolationException> {
@Override
public Response toResponse(ResteasyReactiveViolationException exception) {
// Handle the exception and return a response
return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();
}
}