本文整理匯總了Java中javax.ws.rs.ext.ExceptionMapper類的典型用法代碼示例。如果您正苦於以下問題:Java ExceptionMapper類的具體用法?Java ExceptionMapper怎麽用?Java ExceptionMapper使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ExceptionMapper類屬於javax.ws.rs.ext包,在下文中一共展示了ExceptionMapper類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: toResponse
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@SuppressWarnings({ "unchecked", "rawtypes" })
private Response toResponse(final MinijaxRequestContext context, final Exception ex) {
final MinijaxResourceMethod rm = context.getResourceMethod();
final List<MediaType> mediaTypes;
if (rm != null) {
mediaTypes = rm.getProduces();
} else {
mediaTypes = context.getAcceptableMediaTypes();
}
for (final MediaType mediaType : mediaTypes) {
final ExceptionMapper mapper = providers.getExceptionMapper(ex.getClass(), mediaType);
if (mapper != null) {
return mapper.toResponse(ex);
}
}
return ExceptionUtils.toWebAppException(ex).getResponse();
}
示例2: register
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@SuppressWarnings("unchecked")
public void register(final Class<?> c) {
if (MessageBodyReader.class.isAssignableFrom(c)) {
readers.add((Class<MessageBodyReader<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Consumes.class)));
}
if (MessageBodyWriter.class.isAssignableFrom(c)) {
writers.add((Class<MessageBodyWriter<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
}
if (ExceptionMapper.class.isAssignableFrom(c)) {
exceptionMappers.add((Class<ExceptionMapper<?>>) c, MediaTypeUtils.parseMediaTypes(c.getAnnotation(Produces.class)));
}
if (ParamConverterProvider.class.isAssignableFrom(c)) {
paramConverterProviders.add((ParamConverterProvider) application.get(c));
}
}
示例3: doBatch
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
/**
* Process the entries
*/
private void doBatch() {
for (final B importEntry : task.getEntries()) {
// Override previous status
importEntry.setStatus(null);
importEntry.setStatusText(null);
try {
doBatch(importEntry);
// Success
importEntry.setStatus(Boolean.TRUE);
log.info("Import of {} succeed", importEntry);
} catch (final Exception ne) {
// The entry creation failed : entity itself of group membership
log.info("Import of {} failed : {}", importEntry, ne.getMessage());
importEntry.setStatus(Boolean.FALSE);
final ExceptionMapper<Throwable> mapper = jaxrsFactory.createExceptionMapper(ne.getClass(), null);
importEntry.setStatusText(mapper == null ? ne.getMessage() : mapper.toResponse(ne).getEntity().toString());
}
task.getStatus().setDone(task.getStatus().getDone() + 1);
}
}
示例4: configureMessage
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@Test
public void configureMessage() throws IllegalArgumentException, IllegalAccessException {
final ServerProviderFactory instance = ServerProviderFactory.getInstance();
@SuppressWarnings("unchecked")
final List<ProviderInfo<ExceptionMapper<?>>> object = (List<ProviderInfo<ExceptionMapper<?>>>) FieldUtils
.getField(ServerProviderFactory.class, "exceptionMappers", true).get(instance);
final FailSafeExceptionMapper provider = new FailSafeExceptionMapper();
object.add(new ProviderInfo<>(provider, null, true));
final JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
FieldUtils.getField(FailSafeExceptionMapper.class, "jacksonJsonProvider", true).set(provider, jacksonJsonProvider);
final UserImportEntry entry = Mockito.mock(UserImportEntry.class);
Mockito.when(entry.getId()).thenThrow(new RuntimeException());
final BatchTaskVo<UserImportEntry> importTask = new BatchTaskVo<>();
importTask.setEntries(Collections.singletonList(entry));
task.configure(importTask);
task.jaxrsFactory = instance;
task.run();
Assert.assertEquals(Boolean.TRUE, importTask.getStatus().getStatus());
Assert.assertEquals(1, importTask.getStatus().getDone());
Assert.assertEquals(1, importTask.getStatus().getEntries());
}
示例5: toResponse
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@Override
public Response toResponse(Exception ex) {
if (Options.RETURN_EXCEPTION_BODY) {
if (ex instanceof PersistenceException) {
Throwable cause = ex.getCause();
if (cause != null) { // The type of this exception is determined at runtime
cause = cause.getCause();
if (cause instanceof SQLIntegrityConstraintViolationException) {
return new RestErrorBuilder(cause).createResponse();
}
}
}
}
ExceptionMapper exceptionMapper = providers.getExceptionMapper(ex.getClass());
if (exceptionMapper == null || exceptionMapper == this) {
return Response.serverError().build();
}
else {
return exceptionMapper.toResponse(ex);
}
}
示例6: backstopperOnlyExceptionMapperFactory_removes_all_exception_mappers_except_Jersey2ApiExceptionHandler
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@Test
public void backstopperOnlyExceptionMapperFactory_removes_all_exception_mappers_except_Jersey2ApiExceptionHandler()
throws NoSuchFieldException, IllegalAccessException {
// given
AbstractBinder lotsOfExceptionMappersBinder = new AbstractBinder() {
@Override
protected void configure() {
bind(JsonMappingExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
bind(JsonParseExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
bind(generateJerseyApiExceptionHandler(projectApiErrors, utils)).to(ExceptionMapper.class);
}
};
ServiceLocator locator = ServiceLocatorUtilities.bind(lotsOfExceptionMappersBinder);
// when
BackstopperOnlyExceptionMapperFactory overrideExceptionMapper = new BackstopperOnlyExceptionMapperFactory(locator);
// then
Set<Object> emTypesLeft = overrideExceptionMapper.getFieldObj(
ExceptionMapperFactory.class, overrideExceptionMapper, "exceptionMapperTypes"
);
assertThat(emTypesLeft).hasSize(1);
ServiceHandle serviceHandle = overrideExceptionMapper.getFieldObj(emTypesLeft.iterator().next(), "mapper");
assertThat(serviceHandle.getService()).isInstanceOf(Jersey2ApiExceptionHandler.class);
}
示例7: toResponse
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
public Response toResponse(EJBException exception)
{
if (exception.getCausedByException() == null)
{
return Response.serverError().build();
}
Class cause = exception.getCausedByException().getClass();
ExceptionMapper mapper = providers.getExceptionMapper(cause);
if (mapper == null)
{
return Response.serverError().build();
}
else
{
return mapper.toResponse(exception.getCausedByException());
}
}
示例8: toResponse
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@SuppressWarnings("unchecked")
@Override
public Response toResponse(EJBException exception) {
if (exception.getCausedByException() == null) {
LOGGER.error(exception.getMessage(), exception);
return Responses.errorResponse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(), "Internal Server Error", exception, LOGGER.isInfoEnabled());
} else {
Class cause = exception.getCausedByException().getClass();
ExceptionMapper mapper = providers.getExceptionMapper(cause);
if (mapper == null) {
LOGGER.error(exception.getMessage(), exception);
return Responses.errorResponse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(), "Internal Server Error", exception, LOGGER.isInfoEnabled());
} else {
return mapper.toResponse(exception.getCausedByException());
}
}
}
示例9: getClasses
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
// rest Resources
Set<Class<? extends RESTResource>> restResourceTypes = this.getRESTResourceTypes();
if (CollectionUtils.hasData(restResourceTypes)) s.addAll(restResourceTypes);
// Request received objects mappers: transforms Java->XML for REST methods param types
Set<Class<? extends MessageBodyReader<?>>> reqReceivedTypesMappers = this.getRequestReceivedTypesMappers();
if (CollectionUtils.hasData(reqReceivedTypesMappers)) s.addAll(reqReceivedTypesMappers);
// Response sent objects mappers: transforms Java->XML for REST methods return types
Set<Class<? extends MessageBodyWriter<?>>> respSentTypesMappers = this.getResponseSentTypesMappers();
if (CollectionUtils.hasData(respSentTypesMappers)) s.addAll(respSentTypesMappers);
// Exception Mappers
Set<Class<? extends ExceptionMapper<?>>> expsMappers = this.getExceptionsMappers();
if (CollectionUtils.hasData(expsMappers)) s.addAll(expsMappers);
return s;
}
示例10: init
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
public void init() {
for (Map.Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Path.class).entrySet()) {
log.info("Deploying " + entry.getKey() + " bean as a resource");
deploy(entry.getValue());
}
for (Map.Entry<String, ExceptionMapper> exceptionMapper :
applicationContext.getBeansOfType(ExceptionMapper.class).entrySet()) {
log.info("Adding " + exceptionMapper.getKey() + " ExceptionMapper");
addExceptionMapper(exceptionMapper.getValue());
}
configureTransport(applicationContext.getBeansOfType(ListenerConfiguration.class).values(),
applicationContext.getBeansOfType(TransportConfig.class).values());
start();
}
示例11: addExceptionMapper
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
public void addExceptionMapper(ExceptionMapper... mapper) {
Arrays.stream(mapper).forEach(em -> {
Arrays.stream(em.getClass().getMethods()).
filter(method -> "toResponse".equals(method.getName()) && method.getParameterCount() == 1 &&
!Throwable.class.getName().equals(method.getParameterTypes()[0].getTypeName())).
findAny().
ifPresent(method -> {
try {
exceptionMappers.put(Class.forName(method.getParameterTypes()[0].getTypeName(), false,
em.getClass().getClassLoader()), em);
} catch (ClassNotFoundException e) {
log.error("Could not load class", e);
}
});
});
}
示例12: handleThrowable
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
private void handleThrowable(MicroservicesRegistryImpl currentMicroservicesRegistry, Throwable throwable,
Request request) {
Optional<ExceptionMapper> exceptionMapper = currentMicroservicesRegistry.getExceptionMapper(throwable);
if (exceptionMapper.isPresent()) {
org.wso2.msf4j.Response msf4jResponse = new org.wso2.msf4j.Response(request);
msf4jResponse.setEntity(exceptionMapper.get().toResponse(throwable));
msf4jResponse.send();
} else {
log.warn("Unmapped exception", throwable);
try {
HTTPCarbonMessage response = HttpUtil.createTextResponse(
javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Exception occurred :" + throwable.getMessage());
response.addHttpContent(new DefaultLastHttpContent());
request.respond(response);
} catch (ServerConnectorException e) {
log.error("Error while sending the response.", e);
}
}
}
示例13: getExceptionProviderMap
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
/**
* Finds the RESTEasy providers parameter and return its value as map of classes with its generic types.
*
* @param contextParams the map of all context parameters
* @return a Map of RESTEasy exception-provider classes
*/
public static Map<Class<?>, Class<?>> getExceptionProviderMap(Map<String, String> contextParams) {
Map<Class<?>, Class<?>> providerMap = new HashMap<Class<?>, Class<?>>();
List<String> providers = getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS);
if (providers != null) {
for (String provider : providers) {
Class<?> providerClass = Classes.forName(provider.trim());
if (providerClass != null) {
Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ExceptionMapper.class)[0];
Class<?> exceptionClass = Types.getRawType(exceptionType);
providerMap.put(exceptionClass, providerClass);
}
}
}
return providerMap;
}
示例14: mapException
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
/**
* Maps an ExceptionMapper for a given type of Exceptions. While this method
* can be used for arbitrary exceptions, it is most useful to override the
* default exception handlers defined in LinkRest for the following
* exceptions: {@link LinkRestException}, {@link CayenneRuntimeException},
* {@link ValidationException}.
*
* @since 1.1
*/
public <E extends Throwable> LinkRestBuilder mapException(Class<? extends ExceptionMapper<E>> mapper) {
for (Type t : mapper.getGenericInterfaces()) {
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
if (ExceptionMapper.class.equals(pt.getRawType())) {
Type[] args = pt.getActualTypeArguments();
exceptionMappers.put((Class<?>) args[0], mapper);
return this;
}
}
}
throw new IllegalArgumentException("Failed to register ExceptionMapper: " + mapper.getName());
}
示例15: useAllExceptionMappers
import javax.ws.rs.ext.ExceptionMapper; //導入依賴的package包/類
@Test
public void useAllExceptionMappers() {
final TenacityConfiguredBundle<Configuration> bundle = TenacityBundleBuilder
.newBuilder()
.configurationFactory(CONFIGURATION_FACTORY)
.mapAllHystrixRuntimeExceptionsTo(429)
.build();
assertThat(bundle)
.isEqualTo(new TenacityConfiguredBundle<>(
CONFIGURATION_FACTORY,
Optional.empty(),
ImmutableList.<ExceptionMapper<? extends Throwable>>of(
new TenacityExceptionMapper(429),
new TenacityContainerExceptionMapper(429))
));
}