I wanna return the details of exception with ABP .NET Core, what I noticed is when I go to AbpAuditLogs table and App_Data\Logs logFile they contain the exception in details but when I use below method to return the exception it shows only general exception without any details (500 Internal Server Error)
try{
:
:
:
}
catch (Exception ex)
{
throw new System.ArgumentException(ex.InnerException.Message.ToString(), "original");
}
So, How could I return the specific Exception for the user for Example Email Validation Exception and so on?
Update:
I will explain more to make the question more clear :
The way that I handled the exception is attached with this question above .
The problem is when hitting a request on the service from swagger or Postman always see General Error with status Code 500 without any details and that force me to review the details of the exception from Log File or Log Table , I wanna see the details of the exception (e.g FileNotFoundException ) directly from Swagger or Postman without return back to Log File or AbpAuditLogs Table.
I think User Friendly Exception will work for you.
Because if an exception implements the IUserFriendlyException interface, then ABP does not change it's Message and Details properties and directly send it to the client.
throw new UserFriendlyException(
"Username should be unique!"
);
You can find more information here.
Actually, I found the answer in this question for #Mehdi Daustany .what I did is exactly what #Mehdi Daustany answered, I've added below code :
if (_env.EnvironmentName.ToLower() == "development")
Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;
under ***.Web.Core then the details of exception appeared in the Swagger
services.Configure<AbpExceptionHandlingOptions> (options =>
{
options.SendExceptionsDetailsToClients = true;
});
Above code will configure abp to return all the exception details. Just add it to the configuration.
Related
I have a very specific question, and i really searched the answer all over the place...
Here is a situation: i have a Scatter-Gather component with a custom aggregation strategy.
http://clip2net.com/s/j66jK8 - Image of a subflow
Semantic of this process is rather simple. Request comes with Basic Authentication Header, the upper road calls just empty java processor, which returns original payload, the lower road authenticates user over LDAP, and returns Boolean result of this authentication process. Custom aggregation class checks result and if authentication was OK, then returns original payload, which results from the road #1. If not OK, then throws exception. Nothing wrong here, it works.
There is a bit tricky thing. If a user passed wrong authentication data then exception occurs in ldap:bind module. According to documentation exception is propagated to the Scatter-Gather so i'm trying to catch it using this:
#Override
public MuleEvent aggregate(AggregationContext context) throws MuleException {
for (MuleEvent event: context.collectEventsWithExceptions()) {
event.getMessage().getExceptionPayload().getException().printStackTrace();
throw new RuntimeException(event.getMessage().getExceptionPayload().getException());
}
MuleEvent result = DefaultMuleEvent.copy(context.getEvents().get(0));
if (!(Boolean) context.getEvents().get(1).getMessage().getPayload()) {
throw new SecurityException();
}
return result;
}
BUT!
As a result i see exception which stacktrace does not have javax.naming.AuthenticationException which was rased by ldap:bind component, and was printed to log automaticaly (see below).
So, my question is: how can i reach and rethrow this javax.naming.AuthenticationException exception out of Custom Aggregation Class?
I'd appreciate all you ideas and help. Thank you in advance.
WARN 2014-10-15 20:51:18,552 [[minkult].ScatterGatherWorkManager.02] org.mule.module.ldap.api.jndi.LDAPJNDIConnection: Bind failed.
ERROR 2014-10-15 20:51:18,559 [[minkult].ScatterGatherWorkManager.02] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Work Descriptor. Root Exception was: javax.naming.AuthenticationException: [LDAP: error code 49 - INVALID_CREDENTIALS: Bind failed: Attempt to lookup non-existant entry: cn=sim,ou=people,dc=example,dc=com]; resolved object com.sun.jndi.ldap.LdapCtx#5de37d66. Type: class javax.naming.AuthenticationException
COUNT: 1
org.mule.api.transport.DispatchException: route number 1 failed to be executed. Failed to route event via endpoint: InterceptingChainLifecycleWrapper 'wrapper for processor chain 'null''
[
ScriptComponent{CheckAuth.component.553657235},
org.mule.module.ldap.processors.BindMessageProcessor#647af13d,
org.mule.module.ldap.processors.SearchMessageProcessor#2aac6fa7,
InvokerMessageProcessor [name=ldapUtils, object=com.at.mkrf.aggregate.LDAPUtils#5714c7da, methodName=findGroupByName, argExpressions=[#[payload], #[systemName]], argTypes=[Ljava.lang.Class;#5af349a6]
]. Message payload is of type: NullPayload
On a CompositeRoutingException, you can call:
exception.getExceptions().values()
to get an Array of Throwables thrown from within the scatter-gather. Then just re-throw the appropriate exception.
I have a service method which does some operation inside a transaction.
public User method1() {
// some code...
Vehicle.withTransaction { status ->
// some collection loop
// some other delete
vehicle.delete(failOnError:true)
}
if (checkSomething outside transaction) {
return throw some user defined exception
}
return user
}
If there is a runtime exception we dont have to catch that exception and the transaction will be rolled back automatically. But how to determine that transaction rolled back due to some exception and I want to throw some user friendly error message. delete() call also wont return anything.
If I add try/catch block inside the transaction by catching the Exception (super class) it is not getting into that exception block. But i was expecting it to go into that block and throw user friendly exception.
EDIT 1: Is it a good idea to add try/catch arround withTransaction
Any idea how to solver this?? Thanks in advance.
If I understand you question correctly, you want to know how to catch an exception, determine what the exception is, and return a message to the user. There are a few ways to do this. I will show you how I do it.
Before I get to the code there are a few things I might suggest. First, you don't need to explicitly declare the transaction in a service (I'm using v2.2.5). Services are transactional by default (not a big deal).
Second, the transaction will automatically roll back if any exception occurs while executing the service method.
Third, I would recommend removing failOnError:true from save() (I don't think it works on delete()... I may be wrong?). I find it is easier to run validate() or save() in the service then return the model instance to the controller where the objects errors can be used in a flash message.
The following is a sample of how I like to handle exceptions and saves using a service method and try/catch in the controller:
class FooService {
def saveFoo(Foo fooInstance) {
return fooInstance.save()
}
def anotherSaveFoo(Foo fooInstance) {
if(fooInstance.validate()){
fooInstance.save()
}else{
do something else or
throw new CustomException()
}
return fooInstance
}
}
class FooController {
def save = {
def newFoo = new Foo(params)
try{
returnedFoo = fooService.saveFoo(newFoo)
}catch(CustomException | Exception e){
flash.warning = [message(code: 'foo.validation.error.message',
args: [org.apache.commons.lang.exception.ExceptionUtils.getRootCauseMessage(e)],
default: "The foo changes did not pass validation.<br/>{0}")]
redirect('to where ever you need to go')
return
}
if(returnedFoo.hasErrors()){
def fooErrors = returnedFoo.errors.getAllErrors()
flash.warning = [message(code: 'foo.validation.error.message',
args: [fooErrors],
default: "The foo changes did not pass validation.<br/>${fooErrors}")]
redirect('to where ever you need to go')
return
}else {
flash.success = [message(code: 'foo.saved.successfully.message',
default: "The foo was saved successfully")]
redirect('to where ever you need to go')
}
}
}
Hope this helps, or gets some other input from more experienced Grails developers.
Here are a few other ways I've found to get exception info to pass along to your user:
request.exception.cause
request.exception.cause.message
response.status
A few links to other relevant questions that may help:
Exception handling in Grails controllers
Exception handling in Grails controllers with ExceptionMapper in Grails 2.2.4 best practice
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html
How to stop exception from showing in zend framework 2 and instead when exception is thrown i want to redirect to 404 page .
Actually when user fires wrong url or some how any query gets executed in a wrong way exception is thrown , so i need to block this exception and instead redirect to any other well designed page . I'm unable to track the the exception point or rather catch the exception or from where exception is generated . I have used this code
You can handle the exceptions in anyway you want after catching it as the following example in which you are catching the exception globally...:
In the onBootstrap method i have attached the following code in Module.php in a function to execute when an event occurs, the following attach a function to be executed when an error (exception) is raised:
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$em = $application->getEventManager();
//handle the dispatch error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, array($this,
'handleError'));
//handle the view render error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER_ERROR, array($this,
'handleError'));
}
and then defineed in module.php only the function to handle the error
public function handleError(MvcEvent $e)
{
//get the exception
$exception = $e->getParam('exception');
//...handle the exception... maybe log it and redirect to another page,
//or send an email that an exception occurred...
}
I found this code from stackoverflow only , but it is not working , i mean when i'm passing wrong parameters in url , it is showing " A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
Front\Controller\Front
No Exception available "
Please i need help on this.
you can turn off exceptions in zf2 by chaining 'display_exceptions' => TRUE to 'display_exceptions' => false, [module/Application/config/module.config.php]
I am using Active Directory as a data store for the users of my website. I have Active Directory throwing the following exception in case password does not meet any password policy constraint..
-->The password supplied is invalid.
Passwords must conform to the password
strength requirements configured for
the default provider.
Can I customize this error messages/notifications in any way to be them more specific??
What I want is that - If 'password history' is the constraint that is violated then the error message should say so (ex. New password should be different than the last 10 used passwords..)
Any help is appreciated.
you can catch that and throw you own message
try {
// your error will probably appear here
if (MembershipService.ValidateUser(usr, pwd))
{
...
}
}
catch(Exception ex)
{
// Let's see if we have Inner Exceptions to deal
if(ex.InnerException != null)
while(ex.InnerException != null)
ex = ex.InnerException;
// Now, let's check our exception
if(ex.Message.StartsWith("The password supplied is invalid. Passwords must conform to the password strength requirements configured for the default provider."))
{
throw new Exception("My custom message goes here");
}
// Let's throw the original one
throw ex;
}
Is this what you are trying to accomplish?
Well you should see the exact type of Exception that is thrown, and setup a specific catch for this exception.
If you see this link, http://msdn.microsoft.com/en-us/library/0yd65esw.aspx, you will see that you can catch multiple specific Exceptions.
You could then return whatever msg you want to the user.
I'd like my Grails web-app to send an e-mail for each exception that reaches the end-user.
Basically I'm looking for a elegant way to achieve something equivalent to:
try {
// ... all logic/db-access/etc required to render the page is executed here ...
}
catch (Exception e) {
sendmail("exception#example.com", "An exception was thrown while processing a http-request", e.toString);
}
Turns out this exact question was answered on the Grails mailing list a couple of days ago.
The solution is to add the following to the log4j-section of Config.groovy:
log4j {
...
appender.mail='org.apache.log4j.net.SMTPAppender'
appender.'mail.To'='email#example.com'
appender.'mail.From'='email#example.com'
appender.'mail.SMTPHost'='localhost'
appender.'mail.BufferSize'=4096
appender.'mail.Subject'='App Error'
appender.'mail.layout'='org.apache.log4j.PatternLayout'
appender.'mail.layout.ConversionPattern'='[%r] %c{2} %m%n'
rootLogger="error,stdout,mail"
...
// rootLogger="error,stdout" (old rootLogger)
}
Plus adding sun-javamail.jar and activation.jar to the lib/-folder.
Assuming you can do this from groovy, you'll want to use a logging framework such as log4j for this, which has loggers that can append log data to a database, send email, etc.
You could also take a look at exceptionHandler mechanism provided by Grails; I find it very simple; yet powerful enough to take care of all my custom & clean exception handling needs. Haven't tested this approach with 1.1 so far; but works very well with 1.0.3.
class BootStrap {
def exceptionHandler
def init = { servletContext ->
exceptionHandler.exceptionMappings =
[ 'NoSuchFlowExecutionException' :'/myControler/myAction',
'java.lang.Exception' : '/myController/generalAction']
}
def destroy = { }
}
Detailed blog here :
http://blog.bruary.net/2008/03/grails-custom-exception-handling.html