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
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\$