How can I return a custom reponse for a bean validation error under Open Liberty? - bean-validation

We are using beanValidation-2.0 and cdi-2.0 under Open Liberty 20.0.0.3. This works fine in that Open Liberty returns a 400 Bad Request response containing the bean validation error message when a a bean validation error is detected. I would like to update our application to instead return a custom response when Open Liberty detects a bean validation error. Is there a way that I can somehow "intercept" the bean validation error (or the Open Liberty generated response) and return my own custom response?`

Usually when you get a validation error, a ConstraintViolationException is thrown and you should be able to catch that and create your own response.
If you're using JAX-RS, you might want to do this by creating and registering an ExceptionMapper to handle this type of exception and turn it into a response. There's an example here.

You might be able to do this with a custom MessageInterpolator.
It can be specified via the message-interpolator element of validation.xml.

Related

How to get the HTTP-Status from a webMethods com.wm.net.NetException?

How to get the HTTP-Status from a webMethods com.wm.net.NetException?
Is there a way to get the http status code from within the catch block of a java service after calling the pub.client:http service?
If you invoke the pub.client:http from within a flow service, you'll notice that it doesn't throw an exception. For example, a "403 Forbidden" error, will not throw an exception. Instead, it will output to the pipeline a header document.
Within the header document you will find the http status:
When you invoke pub.client:http from within a java service then the invocation is suppose to return an IData object. From that object you should be able to extract the status field using IDataUtil.
So, when you evaluate that the status is not OK, you can throw a ServiceException which will be caught by the flow try/catch.
Hope this helps!

IExceptionHandler does not handle UnsupportedMediaTypeException

I have implemented an exception handler (IExceptionHandler). Its HandleAsync method is called when exceptions are thrown inside controllers.
However, when a wrong content-type is passed with the request and an UnsupportedMediaTypeException is thrown in the formatter, my handler is not called. Instead the default error message is returned
{
"Message": "The request entity's media type...
"ExceptionMessage": "No MediaTypeFormatter ...
...
}
I would like to handle ALL exceptions. What am I missing here?
You need to catch it with a global ExceptionFilterAttribute, and filter HttpResponseException, not UnsupportedMediaTypeException.
E.g.
httpConfiguration.Filters.Add(new MyHttpResponseExceptionFilterAttribute());
It turns out that UnsupportedMediaTypeException is actually wrapped up in an HttpResponseException by the time it hits the WebApi pipeline.
HttpResponseException is not intercepted by IExceptionHandler, because it is designed to transport an HttpResponsMessage out to the client. The UnsupportedMediaTypeException is automatically wrapped into an HttpResponsMessage by the framework, and thrown in a HttpResponseException. The message you see in the HTTP response says "UnsupportedMediaTypeException", but that is actually just the Content of the HttpResponsMessage (HttpResponseException.Response.Content).

How to handle Incorrect JSON syntax in Spring MVC

I have a spring MVC Project, wherein I need to handle incorrect JSON syntax.
Spring MVC throws an error as text/html, which looks like:
Apache Tomcat/7.0.47 - Error report HTTP Status 400 - type Status reportmessage description The request sent by the client was syntactically incorrect.Apache Tomcat/7.0.47
However I want to throw my own exception in JSON format.
Is there any way to do it?
Thanks
I just ran into this as well, here's what I found to fix it:
The Spring MVC docs reference HttpMessageConverter as responsible for converting a #ResponseBody. For JSON, you're likely using a MappingJackson2HttpMessageConverter, which when attempting to convert a message can throw a HttpMessageNotReadableException.
If you have some form of exception handler for that, you can intercept the 400 response.
You can debug to see which Exception is actually thrown (might be a TypeMismatchException or something like that). Then, you can specify an error handler in your controller like
#ExceptionHandler(TypeMismatchException.class)
public String handleTypeMismatchException(TypeMismatchException ex) {
}
Now, in this controller method you can do whatever you want, like passing it the model, request, response etc. You can send to a view, redirect or in your case use a ResponseBody or however else you would like to serve your JSON error.

How to catch AJAX WebMethod errors in global.asax?

I'm using the common practice of catching errors in global.asax in my ASP.net application. In global.asax, I have a function Application_Error that logs the errors to the database.
This works very well to log errors that occur when the user requests a page.
However, this does nothing to help when an asynchronous method (a method decorated with the [WebMethod] attribute) called from the client-side throws an exception. The exception simply bubbles up and may be returned to the client-side code, but I would like to have the error handling code run on the server automatically similar to how page errors are logged in global.asax.
How do I accomplish this? One way would be to wrap every single asynchronous method with try-catch, but this doesn't seem like a good solution to me.
One option is to create an ASP.NET output filter that intercepts and logs WebMethod exceptions sent by ASP.NET to the client. Here's the basic idea:
Create a subclass of Stream that captures the content of the response.
When the stream is closed, check whether the response has a 500 status code as well as a "jsonerror: true" header. If so, the response contains a WebMethod exception; log the exception.
In Global.Application_PostMapRequestHandler, install an instance of this class as the output filter for JSON requests.
For complete source code, see this StackOverflow answer.
How to create a global exception handler for a Web Service

Null Reference getting REMOTE_ADDR

I have an ASMX web service running under IIS7 in classic mode. This service has the following code:
try
{
env.ExternalIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
catch (Exception ex)
{
LogWriter.WriteError(ex);
env.ExternalIP="000.000.000.000";
}
This results in the following stack trace. I only modified the names of usercode call stack here to protect the innocent:
Message: An Exception of type: NullReferenceException occured in method: GetAdditionalServerVar
ExceptionMsg: Object reference not set to an instance of an object.
===Stack Trace===
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
at System.Web.HttpRequest.AddServerVariableToCollection(String name)
at System.Web.HttpRequest.FillInServerVariablesCollection()
at System.Web.HttpServerVarsCollection.Populate()
at System.Web.HttpServerVarsCollection.Get(String name)
at System.Collections.Specialized.NameValueCollection.get_Item(String name)
at MyService.MyMethod()
I'm at a loss here as this is very basic plain vanilla code.
EDIT
This gets even stranger. I have added some basic code just wondering what server variables I can get at this point. This fails with the same exception when I try and get all the keys:
System.NullReferenceException: Object
reference not set to an instance of an
object. at
System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32
index) at
System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String
name) at
System.Web.HttpRequest.AddServerVariableToCollection(String
name) at
System.Web.HttpRequest.FillInServerVariablesCollection()
at
System.Web.HttpServerVarsCollection.Populate()
at
System.Web.HttpServerVarsCollection.get_AllKeys()
at MyService.MyHelper()
When I was looking at the framework code looks like this could happen when the array which caches the server variables isn't populated and it looks like this occurs when there a null pointer to some Context...which seems like a fairly core piece of the framework code.
I suppose it's time to burn up one of our support tickets with Microsoft.
Going through my old questions. I believe this was caused by a bug in either .net or IIS. Essentially, the web service was marked as Oneway. By doing so the user was disconnected before the handler was executed so unless you managed to access the Request variables prior to the handler executing you would encounter a null reference exception.
The workaround was to add an HTTP module which accessed the property earlier in the pipeline before the client was sent the response and the handler was executed.
Have you tried getting the ip directly from HttpContext.Current.Request.UserHostAddress?
It seems that it is not always populated depending on the proxies... http://haacked.com/archive/2006/10/11/A_Gotcha_Identifying_the_Users_IP_Address.aspx

Resources