0
\$\begingroup\$

I have the following snippets. which formats error messages based on a map. I can do it as a simple function call the function for transforming the error. or create a class and handle it in that way.

Functional doesn't require a an object instantiation and the message are exposed so that can imported in test to verify

Object Oriented will more structure but should be instantiated every time its accessed.

Functional

error_handler.js

export const messages = {
 500: 'Unexpected Error Occurred'
 400: 'Bad Request'
}

function transformError(error) {
 const message = messages[error.statusCode]
 return new Error(message)
}

error_handler.spec.js

it('should work for 400',() => {
  const error  = transformError({ statusCode :400 })
  expect(error.message).toEqual(messages[400]);
})
call().catch(transformError)

Object Oriented

class FormattedError {
 constructor(error){
   const messages = {
     500: 'Unexpected Error Occurred'
     400: 'Bad Request'
   }

   return new Error(messages[error.statusCode]);
 }
}

```

```
call().catch(e => new FormattedError(e))
```

```
it('should work for 400',() => {
  const error  = transformError({ statusCode :400 })
  expect(error.message).not.toBe(null)
})
```


What should be the ideal approach consider this is for UI 
\$\endgroup\$
1
  • \$\begingroup\$ A class is generally used to keep track of a state. If you don't need that you might as well use functions. If your whole app is built in an OOP way, you can use static functions in a helper class, such as for example Math.round(). Either way, the code that you wrote seems unwieldy, so it's hard to see what problem you are trying to solve. \$\endgroup\$
    – Kokodoko
    Dec 23, 2019 at 22:01

1 Answer 1

1
\$\begingroup\$

Object oriented doesn't really makes sense to me here. That FormattedError class doesn't even represent anything, just transforming error constructor parameter to another class.

Also you are calling constructor, that then returns instance of something else? I don't know javascript that much so maybe it's some unknown construct to me, but that looks like something terribly wrong.

Edit:

I see no relevance to code being UI code or not.

\$\endgroup\$
2
  • \$\begingroup\$ Yes it doesn't do much. but should one consider the future use cases may be more complex logic on forming the error string? \$\endgroup\$
    – Sreevisakh
    Dec 18, 2019 at 10:19
  • \$\begingroup\$ I mentioned UI code because size of code, limited memory, limited cpu etc when executing in a browser compared to server. \$\endgroup\$
    – Sreevisakh
    Dec 18, 2019 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.