What is the best way to let an Ajax application know about server errors?

Hi I am working on an application with Java, since it is a server language, and for the client side I use Ajax. But I'm pretty new to ajax applications, so I needed some opinions on the issue I was facing. I use Spring Security for authentication and authorization services, and by reading the Spring forums, I have managed to integrate Spring Security with the Ajax application so that ajax requests can be intercepted and appropriate action taken. Here's the problem: what is the best way for the ajax application to know that an error has occurred on the server. What I have done so far is that by convention I am making random http 500+ errors. E. d. for login request I return 550 and 551 for other releases and so on. But I think this is the wrong approach to this. What is the best approach to deal with this situation?

0
source share
3 answers

If the standard HTTP error codes (e.g. 401 Unauthorized) are rich enough, use them. It’s better not to write your own HTTP error codes, they should be fixed. If you need more information to return, you should return a richer object to the response body (serialized, for example, JSON or XML), and parse the client-side object.

+4
source

In my experience, compiling your own HTTP error codes is not the best approach.

  • I know that HTTP protocol stacks and server-side HTTP protocols handle non-standard HTTP status codes as protocol errors.

  • Custom code is likely to confuse error messages if they are treated as non-AJAX responses.

Similarly, the use of the phrase β€œcause” of a part of an answer can be problematic. Some server stacks will not allow you to install it, and some client stacks discard it.

My preferred way to report errors in response to an AJAX request is to send a standard code (e.g. 400 - BAD REQUEST) with an XML, JSON, or plain text response body that gives detailed error information. (Be sure to set the title of the response content type ...)

+2
source

If this is a bug in your application or hack from which you want to protect, just return a general access error. Do not detail the error on the client, as it can be used by a hacker to better understand how to abuse your API. This would still confuse normal users.

If this should be the normal behavior of the application, you might be better off ensuring that you fail by letting you try again later (if that happens), reconnect, or re-authenticate. You should at least admit whether this is a disabled error or an insecure rights error, and display a pleasant explanation to the user.

+1
source

Source: https://habr.com/ru/post/1381773/


All Articles