If exception is thrown in my custom JsonConverter, I want to stop the request and return the error to the client. The problem is that if an exception happens in the converter, the controller method gets the parameter as null and I lose the exception. How can I stop the request from getting to the controller or get the occurred exception from JsonConverter in the controller? Or any other idea..
My converter similar to this post: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
public class MyJsonConverter : JsonConverter
{
protected override Person Create(Type objectType, JObject jObject)
{
Throw new Exception();
}
}
My controller:
Public class MyController : ApiController
{
Public IHttpResuls Post(Person p)
{
...
}
}
I have a solution. Since the HttpContext.Current is null in OWIN web api. You can use this package - OwinRequestScopeContext which allows you to use the context which is also per request.
for example set the error in the JsonConverter:
OwinRequestScopeContext.Current.Items["error"] = exception;
And then get the error in your controller:
var ex = OwinRequestScopeContext.Current.Items["error"] as Exception;
Related
I have a #RestController that returns net.sf.json.JSONObject:
#PostMapping("/list")
public JSONObject listStuff(HttpServletRequest inRequest, HttpServletResponse inResponse) {
JSONObject json = new JSONObject();
...
return json;
}
When JSONObject contains null reference, the following exception is thrown:
Could not write JSON: Object is null; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: net.sf.json.JSONObject[\"list\"]->net.sf.json.JSONArray[0]->net.sf.json.JSONObject[\"object\"]->net.sf.json.JSONNull[\"empty\"])"
This is the legacy code that we are now cleaning up and at some point we will get rid of explicit JSON manipulations, but this will be a huge change, for now I would like to just get rid of the exception.
I tried with following solutions:
Define Include.NON_NULL in Spring's Object Mapper - so this piece of code in my WebMvcConfigurationSupportClass:
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
ObjectMapper webObjectMapper = objectMapper.copy();
webObjectMapper.setSerializationInclusion(Include.NON_NULL);
converters.add(new MappingJackson2HttpMessageConverter(webObjectMapper));
}
Setting following property in application.yml:
spring.jackson.default-property-inclusion=non_null
Checking the version of com.fasterxml.jackson - the only found in the dependency tree is 2.9.7.
None of the above helped.
Any suggestions on how to tell Spring to ignore null values in net.sf.json.JSONObjects?
Include.NON_NULL does not work because JSONNull represents null but it is not null per se. From documentation:
JSONNull is equivalent to the value that JavaScript calls null, whilst
Java's null is equivalent to the value that JavaScript calls
undefined.
This object is implemented as a Singleton which has two methods: isArray and isEmpty where isEmpty is problematic because throws exception. Below snippet shows it's implementation:
public boolean isEmpty() {
throw new JSONException("Object is null");
}
The best way is to define NullSerializer for JSONNull type. Below example shows how we can configure that:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.NullSerializer;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
public class JsonApp {
public static void main(String[] args) throws Exception {
SimpleModule netSfJsonModule = new SimpleModule("net.sf.json");
netSfJsonModule.addSerializer(JSONNull.class, NullSerializer.instance);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(netSfJsonModule);
JSONObject object = new JSONObject();
object.accumulate("object", JSONNull.getInstance());
JSONArray jsonArray = new JSONArray();
jsonArray.add(object);
JSONObject json = new JSONObject();
json.accumulate("list", jsonArray);
System.out.println(mapper.writeValueAsString(json));
}
}
Above code prints:
{
"list" : [ {
"object" : null
} ]
}
See also:
Maven: missing net.sf.json-lib
How do you override the null serializer in Jackson 2.0?
This is not the ideal solution, but rather a workaround. As overriding default mapper/converter behavior didn't work, instead I changed the structure of my JSONObject, so added following line during its generation:
listElt.put("object", "");
which produces:
{
"list" : [ {
"object" : ""
} ]
}
This is fine only if I am not interested in the value of this field - and I am not.
I personally prefer #Michał Ziober's solution - it is elegant and generic. Unfortunately doesn't work for me.
I have a consumer (RabbitListner) in RPC mode and I would like to know if it is possible to throw exception that can be treated by the publisher.
To make more clear my explication the case is as follow :
The publisher send a message in RPC mode
The consumer receive the message, check the validity of the message and if the message can not be take in count, because of missing parameters, then I would like to throw Exception. The exception can be a specific business exception or a particular AmqpException but I want that the publisher can handle this exception if it is not go in timeout.
I try with the AmqpRejectAndDontRequeueException, but my publisher do not receive the exception, but just a response which is empty.
Is it possible to be done or may be it is not a good practice to implement like that ?
EDIT 1 :
After the #GaryRussel response here is the resolution of my question:
For the RabbitListner I create an error handler :
#Configuration
public class RabbitErrorHandler implements RabbitListenerErrorHandler {
#Override public Object handleError(Message message, org.springframework.messaging.Message<?> message1, ListenerExecutionFailedException e) {
throw e;
}
}
Define the bean into a configuration file :
#Configuration
public class RabbitConfig extends RabbitConfiguration {
#Bean
public RabbitTemplate getRabbitTemplate() {
Message.addWhiteListPatterns(RabbitConstants.CLASSES_TO_SEND_OVER_RABBITMQ);
return new RabbitTemplate(this.connectionFactory());
}
/**
* Define the RabbitErrorHandle
* #return Initialize RabbitErrorHandle bean
*/
#Bean
public RabbitErrorHandler rabbitErrorHandler() {
return new RabbitErrorHandler();
}
}
Create the #RabbitListner with parameters where rabbitErrorHandler is the bean that I defined previously :
#Override
#RabbitListener(queues = "${rabbit.queue}"
, errorHandler = "rabbitErrorHandler"
, returnExceptions = "true")
public ReturnObject receiveMessage(Message message) {
For the RabbitTemplate I set this attribute :
rabbitTemplate.setMessageConverter(new RemoteInvocationAwareMessageConverterAdapter());
When the messsage threated by the consumer, but it sent an error, I obtain a RemoteInvocationResult which contains the original exception into e.getCause().getCause().
See the returnExceptions property on #RabbitListener (since 2.0). Docs here.
The returnExceptions attribute, when true will cause exceptions to be returned to the sender. The exception is wrapped in a RemoteInvocationResult object.
On the sender side, there is an available RemoteInvocationAwareMessageConverterAdapter which, if configured into the RabbitTemplate, will re-throw the server-side exception, wrapped in an AmqpRemoteException. The stack trace of the server exception will be synthesized by merging the server and client stack traces.
Important
This mechanism will generally only work with the default SimpleMessageConverter, which uses Java serialization; exceptions are generally not "Jackson-friendly" so can’t be serialized to JSON. If you are using JSON, consider using an errorHandler to return some other Jackson-friendly Error object when an exception is thrown.
What worked for me was :
On "serving" side :
Service
#RabbitListener(id = "test1", containerFactory ="BEAN CONTAINER FACTORY",
queues = "TEST QUEUE", returnExceptions = "true")
DataList getData() {
// this exception will be transformed by rabbit error handler to a RemoteInvocationResult
throw new IllegalStateException("mon expecion");
//return dataHelper.loadAllData();
}
On "requesting" side :
Service
public void fetchData() throws AmqpRemoteException {
var response = (DataList) amqpTemplate.convertSendAndReceive("TEST EXCHANGE", "ROUTING NAME", new Object());
Optional.ofNullable(response)
.ifPresentOrElse(this::setDataContent, this::handleNoData);
}
Config
#Bean
AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) {
var rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(messageConverter);
return rabbitTemplate;
}
#Bean
MessageConverter jsonMessageConverter() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.registerModule(new JavaTimeModule());
var jsonConverter = new Jackson2JsonMessageConverter(objectMapper);
DefaultClassMapper classMapper = new DefaultClassMapper();
Map<String, Class<?>> idClassMapping = Map.of(
DataList.class.getName(), DataList.class,
RemoteInvocationResult.class.getName(), RemoteInvocationResult.class
);
classMapper.setIdClassMapping(idClassMapping);
jsonConverter.setClassMapper(classMapper);
// json converter with returned exception awareness
// this will transform RemoteInvocationResult into a AmqpRemoteException
return new RemoteInvocationAwareMessageConverterAdapter(jsonConverter);
}
You have to return a message as an error, which the consuming application can choose to treat as an exception. However, I don't think normal exception handling flows apply with messaging. Your publishing application (the consumer of the RPC service) needs to know what can go wrong and be programmed to deal with those possibilities.
I'm using Bean Validation with RestEasy in Wildfly 8.2.0.Final:
#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();
}
}
This basically works. Now I'd like to get the response as JSON object but I can't get it working. All my "application" exceptions are handled by my Exception Mapper, this works:
#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 handling
loggingService.log(LogLevel.ERROR, "", ExceptionToStringMapper.map(exception));
return Response.status(Status.INTERNAL_SERVER_ERROR).type(MEDIA_TYPE).entity(responseObject).build();
}
}
But bean validation somehow bypasses it. Then I thought about using Throwable instead of Exception but it didn't help either. I guess the ExceptionMapper is not triggered because there is some life cycle problem with JAX-RS and JSR303. But how can I syncronize them to handle bean validation exceptions?
Additional information: The exception passes the javax.ws.rs.container.ContainerResponseFilter so I could write some workaround by implementing the filter method in a subclass, but this is not clean solution. The target is to handle the exceptions in the Exception mapper.
It's not always the case that your ExceptionMapper<Exception> will catch all exception under the Exception hierarchy. If there is another more specific mapper, say one for RuntimeException, that mapper will be used for all exception of RuntimeException and its subtypes.
That being said (assuming you're using resteasy-validation-provider-11), there is already a ResteasyViolationExceptionMapper that handles ValidationException.
#Provider
public class ResteasyViolationExceptionMapper
implements ExceptionMapper<ValidationException>
This mapper is automatically registered. It returns results in the form of a ViolationReport. The client needs to set the Accept header to application/json in order to see a response similar to
{
"exception":null,
"fieldViolations":[],
"propertyViolations":[],
"classViolations":[],
"parameterViolations":[
{
"constraintType":"PARAMETER",
"path":"get.arg0",
"message":"size must be between 2 and 2147483647",
"value":"1"}
],
"returnValueViolations":[]
}
You can see more at Violation reporting.
If you want to completely override this behavior, you can create a more specific mapper for ResteasyViolationException, which is the exception thrown by the RESTeasy validator
#Provider
public class MyValidationMapper
implements ExceptionMapper<ResteasyViolationException> {
#Override
public Response toResponse(ResteasyViolationException e) {
}
}
I have a Jersey application where I want to prevent the client from seeing any type of stacktrace if any type of Exception occurs.
How do I do this without changing any existing code?
You can register an exception mapper as follows to handle all exceptions and customize the HTTP response:
#Provider
public class MyExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
i need to catch all exceptions of my controllers to a exception controller. How to configure spring?
I need this because every request to my webapp are json request and in case of exception i need to answer with a genericc {success: false, exception: "String ex..."}. But i can not understand if the better way is to use SimpleMappingExceptionResolver.
Thank you.
If you want to write a custom response, it would be more interesting to use a custom HandlerExceptionResolver implementation.
spring configuration:
<bean id="exceptionHandler" class="com.am.CustomHandlerExceptionResolver"/>
java:
public class CustomHandlerExceptionResolver
implements HandlerExceptionResolver {
#Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//write in response
return null;
}
}