Using APIKit in Mule, I need to return a 404 status code if a particular resource is not found when executing my flow.
I can see three ways of handling this:
Throw a custom business exception(using a groovy script) i.e
PersonNotFoundException and use the
apikit:mapping-exception-strategy to map that exception to '404'
Throw the existing Mule exception
org.mule.module.apikit.exception.NotFoundException which is already
mapped to '404'
Do no throw an exception and manually set the http response and
status code within the normal flow of my message.
What's the best practice here? Use exceptions for flow control? and if so use the Mule exception or a custom business exception?
I think this is one of those weird combinations between API best practices and Mule best practices.
For generic resources, ie "/users" I would use the Mule Not Found Exception (404), but for an item resource that does not exist, ie "/users/jim-smith" for usability purposes I would throw a custom exception with "The user requested does not exist" or "You do not have permission to access this user" (status 401) whichever the case may be to best help developers utilizing your API.
I think the biggest advantage to the exception strategy instead of just manually changing the responses yourself is it creates a clear flow where you can easily determine what is a successful response, and what is a failed response.
That and using an exception handler within Mule you can return back a uniform error response to the user (in JSON, XML, etc).
But others might disagree with me, and just manually setting the status code and response yourself does offer the most flexibility, but also allows for inconsistencies.
Related
We have UseExceptionHandler (handle Exeptions) and UseStatusCodePages (handle StatusCode). Why in ASP.NET Core MVC we using StatusCodeResult than just handy extend Exception?
UseExceptionHandler is generally used to catch up unexpected errors and preset them in a more friendly manner to the user.
Whereas status codes are more important in REST API to signal the client the success or failure (and specific cause of the failure) of the specific operation.
Controller action should never throw exception and access a specific resource (i.e. db record) which doesn't exist you should return 404 (not found). When passed data is invalid rest apis return "400 bad request", on success 200. When new resource is created 201 (with "Location" header which contains the url to the new resource, see CreatedAtAction method of the controller class).
With views it works differently where you render the error directly into the HTML Code. You can also return status codes with MVC-esque view controllers and handle it with UseStatusCodePages (i.e. showing a generic NotFound.cshtml template for resources which don't exist).
Also your question sounds like you want to use exceptions to set status code, this is wrong for a couple of reasons.
Exceptions should be (as their name suggest) exceptional; Read: when something unexpected happens. For example if you try to withdraw a negative balance from your bank account and further processing it makes no sense or becomes impossible.
When you expect an error, you should return a result or handle it differently. For validations you should use Result classes (i.e. IdentityResult from ASP.NET Core Identity, which contains a Success property and a property which contains a list of error messages in case the operation or the validation fails).
Throwing and catching Exceptions is quite expensive, so they should really only be thrown when (as pointed above) something unexpected happens. Not finding a record is nothing unexpected.
(Ab)using exceptions for flow control (deciding which code path to execute) is just wrong. That's what if/switch and patterns like strategy pattern are for. Exceptions will just make the code unreadable and harder to maintain.
My goal is to influence the error descriptions that appear in BizTalk Administration Console in the Error Information tab of suspended instance windows, after errors occur in my custom functoids. If possible, I would also like the ErrorReport.Description promoted property to display this error description on the failed message.
I've read everything I can find about custom functoid development, but I can't find much about error handling within them. In particular, whenever my functoids throw exceptions, I see the boilerplate "Exception has been thrown at the target of an invocation" message that occurs whenever exceptions occur through reflection, rather than the message on the exception itself.
I had hoped to find something within the BaseFunctoid class framework that would allow me to submit an error string, so as to traverse the reflection boundary. Is there some way to pass error information from within a custom functoid, such that the BizTalk Administration Console will display it?
If I emulate the approach taken by DatabaseLookupFunctoid and DatabaseErrorExtractFunctoid, is there some way I can fail the map with the extracted error, rather than mapping it to a field on the destination schema as is shown in its examples?
The simplest way to do this is using custom C#, writing something like this in your code:
System.Diagnostics.EventLog.WriteEntry("EVENT_LOG_SOURCE", "Error message...", System.Diagnostics.EventLogEntryType.Error);
As Johns-305 mentions, you need to make sure your event source is registered (e.g. System.Diagnostics.EventLog.CreateEventSource("EVENT_LOG_SOURCE", "Application") - but this should really be done as part of your installation steps with an EventLogInstaller or some kind of script to set up the environment). It's certainly true that error handling in BizTalk is just .NET error handling, but one thing to keep in mind is that maps are actually executing as XSLT, and the context in which their executing can have a major impact on how exceptions and errors will be handled, particularly unhandled exceptions.
Orchestrations
If you're executing a transform in an orchestration that has exception handling in it, the exception thrown will be handled and may even fall into additional logging you have in the orchestration - in other words, executing a throw from a C# functiod will work the way you'd think it would work elsewhere in C#. However, I try to avoid this since you never know if a map will at some point be used else where and because exception handling in XSLT doesn't always work the way you'd think (see below).
Send/Receive Ports
Unfortunately, if you're executing a map on a send or receive port and throw an exception within it, you will almost definitely get very unhelpful error message in the event log and a suspended instance in the group hub. There is no easy, straightforward way to simple "cancel" a transform - XSLT 1.0 doesn't have any specified way of doing that (see for example Throwing an exception from XSLT). That leaves you with outputting an error string to a particular node in the output (and/or to the EventLog), or writing lots of completely custom XSLT to try to validate input, or designing your schemas properly and using a validating component where necessary. For example, if you have a node that must match a particular regex, or should never be empty, or should never repeat more than X times, make sure you set those restrictions on the schema and then make sure you pass it through the XmlValidator or similar before attempting to map.
The simplest answer is, you just do.
Keep in mind, there is nothing special at all about error handling in BizTalk apps, it's just regular plain old .Net error handling.
So, what you do is catch the error in you code, write the details to the Windows Event Log (be sure to create a custom Event Source) and...that's it. That is all I do. I don't worry about what appear in BT Admin specifically.strong text
Is there a way to assert that a flow reference threw an exception in Mulesoft? Searching Google and the documentation isn't turning up anything.
Basically I'm testing a subflow that throws a NotFound exception if a certain item exists, but MUnit fails when it receives the error, even though it's expected.
I know I could mock my validator and have it return specific data which I then check for, but I was hoping there's something native that can do this that's less hacky.
I think what you're looking for is the 'expectException' attribute on the test itself. HTH.
Short and simple:
How to catch pgPL/SQL exceptions with QtSQL?
I haven't found any example or info at the docs.
More details:
I'm developing the front end for a system with Qt 5.3. The database perform some validation at some of the inputs and raise custom exceptions when something is invalid. What I want is to be able to handle these exceptions at he front end code, showing appropriate messages to the user.
EDIT:
I have tried to use the QSqlError class. Although it gave me the exception, it gave me too much data which will need to be parsed to be useful. Is there a way to get the exception raised without parsing the messages?
I developed a rest service by mule, and I want to validate the input params, throws exception when the params is invalid, and the error handler could catch the exception(a custom exception with error code and message included) and get the error code and message which i could return to client.
Currently I use the choice router to evaluate expression, and set the error expression. I think it's awkward, and inconvenient.
I read the document, seems there is no such example, so what's the best way to handle the situation?
If you go beyond a trivial REST resource, using choice routers won't cut it.
You have two better options:
Use JAX-RS + Jersey module: http://www.mulesoft.org/documentation/display/current/Jersey+Module+Reference
Use APIkit: http://www.mulesoft.org/documentation/display/current/APIkit
The former is based on a standard, the latter is proprietary. In the future, the latter will receive most of MuleSoft's attention.