In almost every kind of API there are integer error codes like (ex. 123) which indicates error type. I was wondering if it wasn't better to use descriptive string codes like user_not_found or invalid_request. In my opinion they are much more practical: let's say you get back to your code after months or so and you can easily go through error handling parts without searching for error codes in documentation.
Why integer error codes still exists in APIs?
In an API, clients are usually computers that test for response codes using conditions.
It is much faster to test agains integers than to test agains strings, that's all.
Moreover, error codes have a certain logic: APIs usually use HTTP codes, so when you (as a human) read them, you know that the 2xx indicate success, 4xx indicate client-side errors and 5xx indicate server-side errors, even if you don't know them all by heart.
EDIT:
Your question made me think about this answer, about how loading times in websites affect profits. You should read it to convince yourself that even a few milliseconds sometimes matter.
But there are nice names for most errors. Both standard C, POSIX and Windows have names for their error codes. Of course, most of these names are made as preprocessor macros, but there are also functions to get a nice string or message from these messages.
Related
I do not know how to implement a proprietary handling procedure of user defined errors (routines/algorithm stop) or warnings messages (routine/algorithm can proceed) without using Exceptions (i.e. failwith .... Standard System Exception).
Example: I have a Module with a series of Functions that uses a lot of input data to be checked and to be used to calculate the thickness of a Pressure Vessel Component.
The calculation procedure is complex, iterative and there are a lot of checks to be performed before getting a result, check that can generate "User Defined Errors" that stop the procedure/routine/algorithm or generate a "Warning Messages" proceeding on.
I need to collect these Errors and Messages to be shown to the User in a dedicated form (Wpf or Windows form). This later at the end.
Note: every time that I read a books of F# or C# or Visual basic or an Article in Internet, I found the same Phylosophy/Warning: raise of System/User-Defined Exception should be limited as much as possible: Exception are for unmanageable Exceptional Events ( not predictable) and cause "overload" to the Computer System.
I do not know which handling philosophy to implement. I'm confused. Limited sources available on internet on this particular argument.
Actually I'm planning to adopt this Phylosophy , taken from: "https://fsharpforfunandprofit.com/posts/recipe-part2/". It sounds good for me, ... complex, but good. No other references I was able to go find on this relevant argument.
Question: there are other Phylosophies that I can consider to create this Proprietary handling/collecting of user defined errors? Some books to read or some articles?
My decision will give a big impact on how to design and write my code (splitting problem in several functions, generate a "motor" that run in sequence functions or compose then in different ways depending on results, where to check for Errors/Warnings, how to store Errors and Warning Messages to understand what is going on or where "Errors/Warnings" are genetate and caused "By Which Function"?).
Many thanks in advance.
The F# way is to encode the errors in the types as much as possible. The easiest example is an option type where you would return None if the operation failed ans Some value when it succeeded. Surprisingly, very often this is enough! If not, then you can encode different types of errors AND a success "state" in a discriminated union, e.g.
[<Measure>]
type psi
type VesselPressureResult =
| PressureOk
| WarningApproachingLimit
| ErrorOverLimitBy of int<psi>
and then you will use pattern matching to "decide" what to do in each case. If you need to add more variants, e.g. ErrorTooLow, then you would add that to the DU and then the compiler will "tell" you about all places where you need to fix the logic.
Here is the perfect source with detailed information: https://fsharpforfunandprofit.com/series/designing-with-types.html
We have several large and small Access databases that support users across the state. Recently, I've been trying to add error checking into these datasbases since many where orginally created without it. However, some of these databases have a lot of functions and adding error checking to each one seems overly tedious.
I basically just want the database to send me an email with a description of the error and object/function on which it occurred. Is there an easier way to do this than to add error checking to each function?
While not exactly an answer (or, should I say, not the answer you want), my response to this question holds true in this case as well. In either case, I don't think you can just throw some generic function into your code, or do so without editing every pre-existing function. If proper error trapping is built into your application, you never have to worry about it.
I’ve seen Objective C code using a collection of practices, raging from passing a pointer of NSError for execution finish status - to using NSAssert - to implementing #throw - to relaying on delegate for status code returned in the callback - to the old c method of returning a boolean/int indicating with 1 being success and co.
I can’t identify a consistent pattern for how should I be handling errors happening in my app running on client devices. For ex, what would you recommend handling for the following cases:
Client attempt to access a network resource, network resource timed out / returned 500?
Unexpected state that should have not even happened reached in logical code section?
Attempt to write to disk failed? (Out of disk space, not permission and code)
Coming from Java, server side practices exceptions the weapon of choice, using Objective C and C is seems that exceptions exist but are not encouraged. NSAssert seems harsh, as it will crash the application, which in most cases is not the optimal solution. So, I’d appreciate a Best practices advice.
Exceptions are used to indicate programmer error and/or non-recoverable errors only. Exceptions should not be used for flow control. NSAssert is more of a development tool. Use NSError for recoverable, user addressable (or caused) errors.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorHandling/ErrorHandling.html
First we have to agree upon the terminology. I think there are two types of bad situations in a program: Errors and Exceptions.
Errors An unwanted situation that can happen but you can recover from it with the program memory being in a consistent state and further execution can continue.
eg1. Client attempt to access a network resource, network resource timed out / returned 500?
eg2. Attempt to write to disk failed? (Out of disk space, not permission and code)
Approach Handle the error the way you want it handled. Show user message, log it to file/console, report it to your back-end if you think it needs to be reported.
Exceptions A state that should never have been reached and may corrupt the memory state of the app in a way that prevents further execution.
This could happen at two levels.
Level 1 A logic error that you have overlooked and is now causing the exception.
eg1. accessing invalid array elements i.e. index out of bound exception.
In the above example, you unconsciously made a programming mistake. You couldn't have handled it because you overlooked it. This will crash the application.
Approach Your approach here should be to identify the bug and fix it. In the process some end users will be affected which is the case with the most meticulous software.
Level 2
As you are programming, you come across a situation that your business logic doesn’t permit.
eg1. Unexpected state that should have not even happened reached in logical code section?
eg2. A database entry that you always expect to be present as per your business logic. For example, let's say you are making an app that requires a currency table with currency names, unicode symbols for currencies and country names. The value from this table are to be shown as a drop down in your UI. You may create a table upon first launch of the app and insert the values or may be you ship the table in the bundle but you always expect it to have the values you are inserting. You make an sqlite select query->sqlite execution succeeds->but no values are returned. Business logic demands that values should be present but for some mysterious reason they are absent.
Here is where most confusion stems from because sometimes you can recover from some of these situations by treating them as errors and displaying a message to the end user. This approach is wrong. This is an exception at business logic level. One that you should prevent from happening.
Approach You should force crash the app here as well using NSAsserts both in development and production mode. This is an aggressive approach and some end users will be affected, but I have read experts advising to adopt an aggressive approach to finding bugs and remedying them rather than pretending they don’t exist or thinking you have smartly covered them all when all you have done is masking exceptions as errors through your “handling tactics”. I believe the experts are right. Coming from Java, you may find it a very objCeee.. way of doing things.
Nils and Bools You should understand that they are just facilitators to reach at the conclusion of whether you treat something as an error or exception. They are not the end in themselves. While writing your methods with return value, you should define what a nil or bool(no) signifies and document your intent on top of the method. Sometimes it would be an error, sometimes it would be an exception, sometimes it could be a normal expected result. While dealing with apple frameworks/third party libraries you should understand what their intent is when they return such values and determine how you want to treat them in your code.
Some other tips
Don’t use #try/catch because experts say so. If you wish to challenge them assuming that Apple has put it there for a reason, Apple is always right, experts(including Apple employees themselves) have got it wrong after all these years, you can go ahead and do it.
Formalize your approach to this->stick to it->document your intent. Don’t think it over and over. Because at some stage error/exceptions/nils/bools would cross the limits of propriety and reach the precincts of taste. You will be better off settling this once and for all and freeing up your time.
I have done some research on how injection/XSS attacks work. it seems like hackers simply make use of the USER INPUT fields to input codes.
However, suppose I restrict every USER INPUT fields with only alphanumerics(a-zA-Z0-9) with preg_replace, and lets assume that I use the soon-to-be-deprecated my_sql instead of PDO or my_sqli.
Would hackers still be able to inject/hack my website?
Thanks!
Short version: Don't do it.
Long version:
Suppose you have
SELECT * FROM my_table WHERE id = $user_input
If this happens, then some inputs (such as CURRENT_TIMESTAMP) are still possible, though the "attack" would be limited to the point of probably being harmless. The solution here could be to restrict the input to [0-9].
In Strings ("$user_input"), the problem shouldn't even exist.
However:
You have to make sure you implement your escape function correctly.
It is incredibly annoying for the end user. For instance, if this was a text field, why aren't white spaces allowed? What about á? What if I want to quote someone with ""? Write a math expression with < (or even write something apparently harmless such as i <3 u)?
So now you have:
A homebrew solution, which has to be checked for correctness (and may have bugs, as any other function). Bugs in this function are potential security issues;
A solution which is unfamiliar to other programmers, who have to get used to it. Code without the usual escape functions is usually wrong code, so it's masssively surprising;
A solution that's fragile. What if someone else modifies your code and forgets to add the validation? What if you forget the validation?
You are focusing on solving a problem that's already been solved. Why waste time doing something that takes time to develop and is hard to maintain when others have already developed proper solutions that take close to no effort to use.
Finally, don't use deprecated APIs. Things are deprecated for a reason. Deprecated can mean stuff like "we'll drop support at any minute" or "this is has severe issues but we can't fix it for some reason".
Deprecated APIs are supposed to be used by legacy applications of developers that did not have enough time or resources to migrate. When starting from scratch, use the supported APIs.
I am investigating an issue with regards to a textbox rejecting user input. In this case the error message is: 'The note was found to contain a possible credit card PAN.'
Now obviously this is a custom validator but I am enable to find where it tells me what characters ARE allowed? In debug I entered a note containing no numbers and when the validators are initialized, these variables have the value below:
valNoteContainsPAN.Expression = Me.PANRegEx
value = (\d*)45367{13,15}(?!\d)
I'm assuming this is blocking numbers of certain lengths? How can I find out how to actually read and understand the above? Google is proving fruitless
For anybody in the same jam as me this website proved extremely helpful:
http://regexhero.net/
It essentially allowed me to enter the coded restriction field and test what would be accepted as well as explaining what each piece of the command actually meant.
This website: http://www.regular-expressions.info/lookaround.html Also gave more of the theory behind it to help me understand what was going on.