try catch in presentation layer - best practice - try-catch

I have a layered architecture application. All the error handling is done at business layer and data layer throws the error to business layer. Presentation layer shows this custom error to user. Along with that I have a common error page where the HTTP related errors are going. I don’t have any try catch block in presentation layer.
But I need to know the best practice to handle the presentation layer error. Assume like the user expect to enter some decimal numbers, but some characters appended along with that. So how can I handle such kind of error? Should I write code to handle that without writing try catch or should have try catch in my presentation layer code?
Another scenario is I am reading one file from a location, but if the file is not present there, then I should catch this in try catch block or presentation or I should write code for all possible errors?
Thanks

For the presentation layer you should validate user entries.
Add validations on the screens. User entries must be validated before being sent to the server. And also validate your model server-side.
For instance if user is requested to enter a decimal value, check that it is actually a decimal value on the client side and server side next to the form submission.
On the page you may mark the fields that are in error with a red box or a red mark on its right side and display the error message just below the field for instance. That is usually how errors are reported to the user.
You may also choose to display the error message as a tooltip but in any case the field in error must be marked as such.
You can check some demo here: http://scotch.io/demos/angular-validation

Related

Should I avoid modifying user inputs before sending to backend if possible?

I'm validating and sanitizing user inputs from the server-side. I'm also validating it from the front-end. But I'm wondering if I should also modify the input values to match the server's requirement before sending a request.
For example, I have a form with a birthday text input in MM-dd format. But the server requires a month(MM) and a day of the month(dd) values separately. I can format the input to match the server's requirement(MM and dd), or I can just pass the value without modification and the server will do the rest. Which method is recommended?
This question is more related to UX practices then frontend itself. I believe that before server validation, frontend checks should be performed.
You shouldn't validate and you definitely shouldn't change any values during user completing the form. However the common practice is to validate fields on blur. This is when you can change fields values.
However I would be very careful with this, to avoid confusing the user. So stripping whitespaces etc. should not be a problem, but aggressive input changes should be avoided.
Also try input masking for operations like date formats.
Check for example this library
https://nosir.github.io/cleave.js/
EDIT:
I case of changing values before sending them to backend, it's perfectly fine. It's good practice to have some mapping layer, which will map between UI forms and DTOs required by backend. UI should be focused on user experience, so some extra work will be required almost every time in more complex scenarios

Validation stages

I am validating with Cake 3 but can't get it working probably.
As the docs says there are two stages of validating:
Before you save your data you will probably want to ensure the data is correct and consistent. In CakePHP we have two stages of validation:
Before request data is converted into entities, validation rules around data types and formatting can be applied.
Before data is saved, domain or application rules can be applied. These rules help ensure that your application’s data remains consistent.
So, if I understand this right, at first validation rules are used when I pass data via newEntity and patchEntity.
After that, the application rules are used when using save or delete.
However, when I am passing data (an array) via newEntity the application rules are never used (buildRules is never called). When using newEntity without passing data, application rules are used!
So, my first question, is it right that not both rules are runned, only one (OR validation rules, OR application rules?). I would expect that first validation rules would be called to check the input, and before saving, ALSO the application rules would be called to check if the entity is valid to the applicaton.
Second question, how should I validate with my API? The actions pass their data via the newEntity method, but I want to check if (for example) the category_id belongs to the same user. Thats typical an application rule I guess?
Thank you very much ;)
Quoting CakePHP documentation:
Validation objects are intended primarily for validating user input, i.e. forms and any other posted request data.
Basically, validation is done when you use newEntity or patchEntity to check that the incoming data is consistent:
You don't have a random string where you should have a number
The user email is of correct format
Standard and confirmation passwords are equals
etc.
Validation is not done when you set field manually:
$user->email = 'not a valid email' ; // no validation check
Basically, validation rules are meant to tell the user « Hey, you did something wrong! ».
Application rules on the other end are always checked when you call save or delete, these may be used for:
Checking uniqueness of a field
Checking that a foreign key exist - There is an Group that correspond to your group_id
etc.
Your first assumption is somehow false because in the following scenario, both validation and application rules are checked:
$article = $this->Articles->newEntity($this->request->data);
$this->Articles->save($article) ;
This part of the documentation explain the difference between the two layers of validation.
Concerning your second question, you should not check that a user has the right to do something in your model, this should be done by your controller, see CakePHP book for more details.

Parsing sqlexception error messages

I'm using C# for end user forms,and what i want to do is to parse the error messages I get from the SQL server.Normally the end user gets the messages like in the picture.Is there a way to parse this and to give the end user what he understands instead of that gibberish there? (like "The Name Test is not permitted in this context .... " as in the picture.)
sql error code
Use Exception.ToString to display a full stack trace. Use Exception.Message to get just the text description part of the error.
In addition, you can look at the SqlException.Class and SqlException.Number properties to make informed decisions about how to handle these exceptions in your code. The SqlException.Number property will correspond to an entry in the sys.messages view. 1205, for example, is the number for a deadlock exception. And if SqlException.Class = 11, then that is a concurrency exception.
The SqlException.Errors property is a list of SqlError objects that contain more detailed information about individual errors. Since a single RPC call to the database can result in multiple exceptions, review these errors to see everything that happened.
exception.ToString() will produce a string like your picture, generally. exception.Message will include just the error message, no stack trace.
When reporting errors in SQL there is always a dilemma where the SQL message needs to convey to the developer what happen, but also provide useful information to a user of the application. We developed a technique of structuring the SQL message into an XML string that provides all the useful information about the error, which allows the caller to use as required. You can see my article on this technique on Code Project at the URL below:
http://www.codeproject.com/Articles/1076477/SQL-Server-Structure-Error-Handling

Whether we can get WM_IME_* messages when we’re typing in WPF TextBox with IME?

First, thanks for reading this thread and provide your suggestion.
Here’s the detailed description of my question: Due to large scale of legacy code, we need to use Win32 messages. And for UI part, we need to use WPF to modernize our appearance. That part of UI need to direct keyboard messages into the old legacy component. For input messages without IME, we have used ComponentDispatcher.ThreadFilterMessage to get these messages like WM_KEYDOWN, WM_CHAR, ect. But for IME input, we can’t get the corresponding WM_IME_* messages. Do we have a way to get these messages, or at least, get all the input text which corresponds to WM_IME_* messages?
We have tried several ways for that:
First, WPF native methods, like OnPreviewKeyDown(), OnTextInput(). One lackage of that solution is that we can’t get the Win32 messages. And I’ve found that WPF will not respond for some special key, e.g. Space key will not cause OnTextInput() to be invoked.
Second, different hooks, like SetWindowLong(), HwndSource.AddHook(). These solutions will not get the WM_IME_* messages as well.
Third, use InputMethod class. I’ve tried to use InputMethod.ImeConversionMode to determine whether the user input corresponds to WM_IME_* messages. But you know it is a different way with ComponentDispatcher.ThreadFilterMessage, and against several basic laws. At the same time, I’m not sure whether there may be cases overlapped for these two ways, and whether there’re missed cases. There’re so many languages and so many kinds of input methods, each of them has different character set and punctuation (They can be combined separately), then that solution will be risky.
When I’m investigating with class ImmComposition, which can be created by TextBoxBase.OnGotKeyboardFocus(), I’ve seen the hook ImmCompositionFilterMessage() is dealing with WM_IME_CHAR(0x0286), but failed to get it in my hook added after base. OnGotKeyboardFocus():
public class HookedTextBox : TextBox
{
protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
base.OnGotKeyboardFocus(e);
InstallHook();
}
}

Usability + showing errors

I am having a discussion with a friend over whether to show or not show entity errors at startup (this is in Silverlight, but can apply to all development techniques).
I made my entry screens so the required fields are immediately marked red so the user knows what the required fields are. He says it's not "the best way" and because of "usability studies", the errors should be shown only when the user enters a value, then removes it again (then the errors should show up).
I think it's just an excuse not having to implement additional code to actually show the errors (because you manually have to validate the entity to retrieve the errors).
What do you think? It would also be very cool if someone could actually post usability studies that back-up one side or the other.
First of all, we need to distinguish between indication of a required field (usually done by putting asterisk (*) next to the field or a little marker "Required" under the field label) and actual validation errors when you highlight the invalid field and provide clear explanation what is wrong. The indication of required fields should be shown from the beginning, so the user, when she opens up the form, can immediately see what information she is required to enter. Such indication is much less intrusive than validation errors.
But situation is different with validation errors. There is no point in showing that the user hasn't entered something until she indicated that she is done with the data entry (by stepping out of the field or by pressing the submit button). Otherwise it is annoying for the user to see those errors when they haven't had a chance to enter the correct information yet.

Resources