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

倾然丶 夕夏残阳落幕 提交于 2019-12-25 03:48:24

问题


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. e. g. 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?


回答1:


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.




回答2:


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 (e.g. 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 ...)




回答3:


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.



来源:https://stackoverflow.com/questions/6243075/whats-the-best-way-to-let-the-ajax-app-know-of-the-errors-back-at-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!