简体   繁体   中英

What's the best way to let the Ajax app know of the errors back at server?

Hi I'm working on an application with Java as it's server-side language and for the client-side I'm using Ajax. But I'm fairly new to ajax applications so I needed some opinions on the issue I've faced. I'm using Spring Security for my authentication and authorization services and by reading spring forums I've managed to integrate Spring Security with Ajax application in a way that ajax requests can be intercepted and relevant action be taken. Here's the issue: What is the best way to let the ajax application know that an error has occurred back at server. What I've been doing so far is that by convention I make random http 500+ errors. eg to prompt for login I return 550, and 551 for other issue and so forth. But I think this is not the right approach to this. What is the best approach for dealing with this situation?

If standard HTTP error codes (eg 401 Unauthorized) are rich enough, use them. Best not to make up your own HTTP error codes, they're meant to be fixed. If you need more info to be returned, you should return a richer object in the response body (serialized as eg JSON or XML) and parse the object on the client side.

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

  • I've known client and server-side HTTP protocol stacks to treat non-standard HTTP status codes as protocol errors.

  • A non-standard code is likely to lead to confusing error messages if they end up being handled as non-AJAX responses.

Similarly, using the "reason phrase" part of the response can be problematic. Some server-side stacks won't let you set it, and some client-side stacks discard it.

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

If this a bug in your application or a hack that you want to protect from, just return a generic access error. Don't give detail of the error on the client as it could be used by the hacker to better understand how to abuse your API. This would confuse normal users anyway.

If this is to be normal application behaviour, it might be better to be sure that you fail gracefully by allowing to retry later (if it make sence), reconnect or reauthenticate. You should at least recognise if it is a disconnected error or an insuffiscient rights error, and display a nice looking explanation to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM