OrderNotFoundException extends RuntimeException. Resource ném new OrderNotFoundException(42). Client nhận được gì?
@Provider
public class GenericMapper implements ExceptionMapper<RuntimeException> {
public Response toResponse(RuntimeException e) {
return Response.status(500).entity("error").build();
}
}
@Provider
public class NotFoundMapper implements ExceptionMapper<OrderNotFoundException> {
public Response toResponse(OrderNotFoundException e) {
return Response.status(404).entity(e.getMessage()).build();
}
}
Xem đáp án và giải thích
ExceptionMapper<E> là cơ chế chuẩn để biến exception thành Response, giống @ExceptionHandler trong @ControllerAdvice của Spring. Runtime chọn mapper có kiểu E gần nhất với exception thực tế. Thực tế thường có một mapper tổng quát cho Throwable/RuntimeException (log + 500 không lộ stack trace) và các mapper riêng cho exception nghiệp vụ.