简体   繁体   中英

Approach for ajax error handling with different data structures

I want to use two or three modules to show errors but I have many different error data structures as responses from ajax. Repetitious if/else chains for each ajax error callback or each error display module should be avoided. Here are some examples of error responses I receive in terms of properties to show to the user:

500 Server Error: {
    ...
    Message: "An error has occurred.",
    ...
}

401 Login Error: {
    ...
    Reason: "Invalid login credentials.",
    ...
}

400 Bad Request on Put: {
    Errors: [
        {
            PropertyName: "EmailAddress",
            ErrorName: "Invalid email address."
        }
    ]
}

Currently I'm considering taking each error response through $httpProvider.interceptors in angular (similar to ajaxSetup in jQuery?) and forcing consistent property names onto each one. I don't know if this is bad design, but it would certainly make things easier down the line.

One of the several ways you could solve this is to use two concepts:

Single Responsability principle:

Obviously you can mash everything up and get something working. In my comment I suggested that the Adaptor pattern but when making this an answer I realised that wan't good enough. If so, your application or would still have a part of it's code responsible for choosing the adaptor, so we can encapsulate that into a factory that provides you the proper adaptor:

So we would have three main components:

  • Application: responsible for the app logic, gets the error object and passes it along to...
  • Factory: responsible for analysing the error object and determining which adaptor suites the needs
  • Adaptor(s): responsible for dealing with the error and processing it in a uniform way independently of it's internal format.

In JavaScript this could be something like:

function serviceResponse(error, response) {

  // assuming error could be all different shapes and sizes
  if (error) {

    adaptorFactory
      .getAdaptor(error)
      .process(error)    
  }

  // your valid response logic

} 

Future changes to accommodate new error formats

If you have a new error, you'll have to do two changes, create a new adaptor object and a new if/else in the factory. But the beauty of it is that you will not touch your application logic at all. That serviceResponse method stays exactly as it is

Again, there are plenty of good solutions, this is just one approach. You can develop the adaptor and factory as you wish, as long as the key concepts are kept. My examples were for illustration purposes only.

Hope this helps.

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