Skip to content

Commit

Permalink
feat(error): generic error handler for API requests
Browse files Browse the repository at this point in the history
Merge pull request #11 from lirantal/feat/generic-api-error-handler
  • Loading branch information
lirantal committed Sep 26, 2017
2 parents 3e2644f + ac1ca73 commit f8274cb
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
26 changes: 26 additions & 0 deletions server/lib/helpers/ApiError.js
@@ -0,0 +1,26 @@
'use strict'

const ApiErrorCodes = {
serverError: 'SERVER_ERROR'
}

class ApiError extends Error {
constructor (message, {status, code} = {}) {
super(message)

// Set HTTP status code
this.status = status || 500

// Set API error code
this.code = code || ApiErrorCodes.serverError

// Ensures that stack trace uses our subclass name
this.name = this.constructor.name

// Ensures the ApiError subclass is sliced out of the
// stack trace dump for clarity
Error.captureStackTrace(this, this.constructor)
}
}

module.exports = ApiError
8 changes: 6 additions & 2 deletions server/lib/services/express.js
Expand Up @@ -166,8 +166,12 @@ module.exports.initErrorRoutes = function (app) {
// Log it
console.error(err.stack);

// Redirect to error page
res.status(500).send();
// Build an error response object and send it with the
// status in the error
res.status(err.status).send({
message: err.message,
code: err.code
});
});
};

Expand Down
Expand Up @@ -5,6 +5,7 @@
*/
const path = require('path')
const config = require(path.resolve('./lib/config'))
const ApiError = require(path.resolve('./lib/helpers/ApiError'))
const errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'))
const mongoose = require('mongoose')
const passport = require('passport')
Expand All @@ -22,12 +23,12 @@ var noReturnUrls = [
/**
* Signup
*/
exports.signup = async function (req, res) {
exports.signup = async function (req, res, next) {
try {
const user = await UserService.signUp(req.body)
return res.json(user)
} catch (err) {
return res.status(500).send(err.message)
return next(new ApiError(err.message))
}
}

Expand All @@ -49,7 +50,7 @@ exports.signout = function (req, res) {
/**
* Jwt Token Auth
*/
exports.token = async function (req, res) {
exports.token = async function (req, res, next) {
try {
// Authenticate the user based on credentials
// @TODO be consistent with whether the login field for user identification
Expand All @@ -69,7 +70,7 @@ exports.token = async function (req, res) {

res.status(200).json({token: token})
} catch (err) {
return res.status(500).send(err.message)
return next(new ApiError(err.message))
}
}

Expand Down

0 comments on commit f8274cb

Please sign in to comment.