danivek/json-api-serializer

Support extracting error class names into the 'title' field of JSON API errors

calmcl1 opened this issue · 1 comments

Perhaps when serializing errors using serializeError, instead of just having a basic Error document returned like

const error = new Error('An error occurred');
Serializer.serializeError(error)

returning:

{ errors: [
    { detail: 'An Error occurred' }
]}

Would it perhaps be helpful if the class name of the error was extracted into the title field of the JSON:API error object, resulting in:

{ errors: [
    { detail: 'An Error occurred',
      title: 'Error'
    }
]}

This might seem trivial at first, but it could allow for greater clarity when users might be subclassing their own errors to return, like this:

class AuthError extends Error { }
const err = new AuthError('Authentication token was not provided')
Serializer.serializeError(error)

becomes

{ errors: [
    { detail: 'Authentication token was not provided',
      title: 'AuthError'
    }
]}

or,

class ParameterValueError extends Error { }
const err = new ParameterValueError('Parameter "username" must not contain special characters')
Serializer.serializeError(error)

becomes

{ errors: [
    { detail: 'Parameter "username" must not contain special characters',
      title: 'ParameterValueError'
    }
]}

Perhaps this could be implemented in the serializeError function by using the following in the convertToError internal function:

convertToError(err){
...
    err.title=err.title ? err.title : err.constructor.name
...
}

Interesting 👍, I will add it.