Show SQL error Message in AngularJS - mysql

I'm trying to create an application where the user can explicitly see the SQL rules they're violating if they enter a bad input to be persisted or used to query the database. I would like to show this as a popup message on the browser, also I'm using AngularJS on the client side and SpringBoot on the backend. I've seen the post where they are discussing how to print it on the console,
Show SQL error message.
public static void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
if (ignoreSQLException(
((SQLException)e).
getSQLState()) == false) {
e.printStackTrace(System.err);
System.err.println("SQLState: " +
((SQLException)e).getSQLState());
System.err.println("Error Code: " +
((SQLException)e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while(t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
But in that question it is showing how to retrieve it in the console, not the browser. By default the HttpError message is from SpringBoot where it gives a BadSQLGrammarExcpetion. I require the exact SQLError Message to show the actual error that occurs on the database. I'm a bit new to AngularJS since I'm mainly a backend developer. So if they're are any examples that can be offered I'd really appreciate it.

So I took a different approach...rather than explicitly trying to display the SQL errors which have occurred, based on the scenario which took place I've written my own Exceptions messages and displayed them through the error object. This doesn't give the users too much information so it may lead to security breaches, but just enough to know the problem that has occurred.

Related

Exception details in ABP framework

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.

EntityFramework exception: How can i see the real query

Sometimes i have an EntityFramework exception where calling SaveChanges.
I see this kind of message: "An error occurred while updating the entries. See the inner exception for details."
I have logged the stack trace, the inner exception and stuff but there is no clear explanation of the problem. I would like to see the real query (it is a mysql database), with the parameters. Do you know how i can see or log the real query ?
Thanks
You can use DbEntityValidationException handler which will let you know what was wrong precisely.
try{
//Your code here
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullMessageError = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, "Exact Message " + fullMessageError);
}
catch (Exception ex)
{
//General Exception here
}
You can set log property of dbContext.Database and log the actual queries generated by EF.
using (var context = new MyDBContext())
{
context.Database.Log = Console.Write; // This is where you setup where to log queries
// Your code here...
}
There is a detailed documentation on MSDN https://msdn.microsoft.com/en-us/data/dn469464.aspx

How to Handle RPC Failure error before reach to OnFailure() at client side ? in GWT

In GWT when RPC fail due to any reason at that time onfailure() method execute at client side.
When onFailure() called at that time actual error is visible in browser's Networks response.
So, My Question is simple how can hide / Modify this actual error with some user friendly Error?
You can override onFailure() method to display what you need, but you cannot modify what a browser shows in the Network tab.
This is an example from my code (LoginException and VersionException are exceptions that my RPC calls throw when necessary):
#Override
public void onFailure(Throwable caught) {
if (caught instanceof LoginException) {
// Redirect a user to login page
Window.Location.assign("/");
} else if (caught instanceof IncompatibleRemoteServiceException ||
caught instanceof VersionException) {
/*
* Here I tell a user that a new version is available,
* so a user needs to refresh the page
*/
} else {
// Here I show a simple message about a connection error
}
}

Typo3 scheduler handling exceptions?

I'm currently programming a scheduler task to run in my typo3 backend. For more security and a better debuggable workflow I want to throw exceptions that get displayed in the "scheduled tasks" section when running a task as well as display a red box rather than a green box because the task has failed. Unfortunately I cant get it work. Returning an exception ends in a printed exception-string with a green/success infobox. When just throw the exception by throw new Exception ends in a red/error infobox with no hint what the exception message was.
public function importCommand($filetype) {
try {
if(!$this->isValidFileTypeConfigured($filetype)) {
throw new \TYPO3\MbxRealestate\Helper\Exception\ImportImmoException('Unsupported filetype "' . $filetype . '" configured in ' . __CLASS__ . '::' . __FUNCTION__);
}
....
} catch (\Exception $ex) {
throw $ex; // throwing ...
return $ex; // or returning
}
return true;
}
You can use the Flash Message API in TYPO3 to output your errors. There are 5 types of errors and respective styling. See here:
http://docs.typo3.org/TYPO3/CoreApiReference/ApiOverview/FlashMessages/Index.html

Handling database connection exceptions with Linq to SQL and Rx

I am trying learn how to best use the Reactive Extensions library and have set up simple test WPF application to view a logging database table. In a ViewModel class I am populating an ObservableCollection with the first 100 log entries from a Linq to Sql DataContext and I'm trying to use Rx to keep the UI responsive.
The following snippet works unless the database is unavailable at which point the app throws an exception and crashes. Where would be the best place to handle database connection exceptions and why are they not handled by the OnError method of the Observer?
ObservableCollection<LogEntry> _logEntries = new ObservableCollection<LogEntry>();
DataContext dataContext = new DataContext( "connection string" );
(from e in dataContext.LogEntries
select e).Take( 100 ).ToObservable()
.SubscribeOn( Scheduler.ThreadPool )
.ObserveOnDispatcher()
.Subscribe( _logEntries.Add, ex => System.Diagnostics.Debug.WriteLine( ex.ToString() ) );
Try this instead of ToObservable:
public static IObservable<T> SafeToObservable(this IEnumerable<T> This)
{
return Observable.Create(subj => {
try {
foreach(var v in This) {
subj.OnNext(v);
}
subj.OnCompleted();
} catch (Exception ex) {
subj.OnError(ex);
}
return Disposable.Empty;
});
}
In general though, this isn't a great use of Rx since the data source isn't very easy to Rx'ify - in fact, the code will execute most of the work on the UI thread, send it out to random worker threads, then send it back (i.e. completely wasted work). Task + Dispatcher.BeginInvoke might suit you better here.