I am attempting to use exceptions to display errors in my aura application. As per documentation, the only way to return a meaningful error from code is to throw AuraHandledException. The problem is that the class is not extensible (non-virtual) meaning that only a custom message property is returned as part of the exception. Is there a way to use some other exception class that can be extended to include more attributes and that would be handled in the same way AuraHandledException is?
-
What additional attributes are you trying to add to your error?– TrevorBlissCommented Nov 28, 2016 at 19:15
-
I would like to add details of the dml errors. That would allow mapping of errors to the fields on the screen or applying certain logic/styling around it.– ArturCommented Nov 28, 2016 at 20:40
2 Answers
I ended up JSON-encoding the message for AuraHandledException and attempting to parse the JSON inside the javascript callback. If parsing fails, I assume the message is a string and use it instead. This allows me to pass any structured error response that I need now or in the future. Not saying that it is the right way to do things but I don't see an alternative at the moment.
AuraHandledException
is a quick way to tell the client to throw an error and display your custom message, gracefully. If you want to "handle" the error on the client, then you should do so by catching the exception on the server and returning your custom result with more information as to how the client should behave:
var state = response.getState();
if (state === "SUCCESS") {
var response = response.getResponseValue();
if(response.hasError) {
switch(response.errorCode) {
case 403: throw new Error("You don't have permission"); break;
// bad request eg. bad parameters sent to server
case 400: helper.showInlineErrorMessageInForm(); break;
}
}
else {
helperProcessSuccess();
}
}
-
That seems to be more of a workaround as when you handle the server exception and return the response in that way, you also need to handle the rollback of everything you have done. I would prefer to use the exception mechanism as the functionality is already pre-built for it to minimize the code required both on server and client side.– ArturCommented Nov 28, 2016 at 12:37
-
@Artur have you tried throwing a custom exception on the server, then handling that in the state == "ERROR" in your client callback? Commented Nov 28, 2016 at 12:46
-
I tried both standard exceptions and custom exceptions that extend Exception class. Both return something similar to: An internal server error has occurred Error ID: 1726879261-336513 (119852647) when not wrapped via AuraHandledException. I think it would be a lot easier if standard class AuraHandledException could be extended. :(– ArturCommented Nov 28, 2016 at 13:00
-
Did you add an error state handler to your action callback like I mentioned above? Commented Nov 28, 2016 at 13:42
-