How to use the InternalServerError function from http-errors

Find comprehensive JavaScript http-errors.InternalServerError code examples handpicked from public code repositorys.

http-errors.InternalServerError is a JavaScript class that creates an error object representing an HTTP 500 Internal Server Error.

131
132
133
134
135
136
137
138
139
140
unavailableForLegalReasons: function unavailableForLegalReasons (message) {
  return new createError.UnavailableForLegalReasons(message)
},

internalServerError: function internalServerError (message) {
  const error = new createError.InternalServerError(message)
  // mark error as explicit to allow custom message
  error.explicitInternalServerError = true
  return error
},
fork icon30
star icon340
watch icon17

+ 55 other calls in file

36
37
38
39
40
41
42
43
44
45
    if (!_.includes(['GET', 'HEAD'], req.method) || !req.accepts('html')) {
      return next()
    }
    res.sendFile(filename, err => {
      if (err) {
        next(new InternalServerError(err.message))
      }
    })
  }
}
fork icon87
star icon200
watch icon23

How does http-errors.InternalServerError work?

http-errors.InternalServerError is a constructor function that creates an error object with the status code, message, and other properties required for a server error response. It extends the http-errors.HttpError constructor, setting the status code to 500 by default, and can also include a stack property with a stack trace for debugging.

128
129
130
131
132
133
134
135
136
    .value()
}

function isServiceAccountReady ({ type, object: serviceAccount }) {
  if (type === 'DELETE') {
    throw new InternalServerError('ServiceAccount resource has been deleted')
  }
  return !_.isEmpty(getFirstServiceAccountSecret(serviceAccount))
}
fork icon87
star icon0
watch icon0

133
134
135
136
137
138
139
140
141
142
_.set(body, 'data.createdBy', user.id)
let project = await client['core.gardener.cloud'].projects.create(toResource(body))

const isProjectReady = ({ type, object: project }) => {
  if (type === 'DELETE') {
    throw new InternalServerError('Project resource has been deleted')
  }
  return _.get(project, 'status.phase') === 'Ready'
}
const timeout = exports.projectInitializationTimeout
fork icon87
star icon0
watch icon0

Ai Example

1
2
3
4
5
6
7
const createError = require("http-errors");

try {
  // some code that might throw an error
} catch (err) {
  throw createError(500, "Internal Server Error");
}

In this example, we are using http-errors to create a new InternalServerError with a status code of 500 and a message of 'Internal Server Error'. We then throw this error so that it can be caught and handled by an error handler middleware or other function in the application.

131
132
133
134
135
136
137
138
139
140
unavailableForLegalReasons: function unavailableForLegalReasons (message) {
  return new createError.UnavailableForLegalReasons(message)
},

internalServerError: function internalServerError (message) {
  return new createError.InternalServerError(message)
},

notImplemented: function notImplemented (message) {
  return new createError.NotImplemented(message)
fork icon30
star icon0
watch icon2

+ 37 other calls in file

13
14
15
16
17
18
19
20
21
      // Telegram error
      if (error.response && error.response.ok === false && error.response.description) {
        throw createError.BadRequest(error.response.description);
      }

      throw createError.InternalServerError();
    }
  });
};
fork icon1
star icon3
watch icon1

117
118
119
120
121
122
123
124
125
126
  // Save the key in the cache
  cache.set(cacheKey, secret)
  return secret
} catch (e) {
  if (e.response) {
    throw InternalServerError(`${errorMessages.jwksHttpError}: [HTTP ${e.response.status}] ${JSON.stringify(e.body)}`)
  }

  e.statusCode = e.statusCode || 500
  throw e
fork icon27
star icon76
watch icon68

+ 15 other calls in file

77
78
79
80
81
82
83
84
85
const url = originalUrl(req);
const org = this._orgRegistry.get(url.hostname);

if (!org) {
    this._log.info(`alias:del - Hostname does not match a configured organization - ${url.hostname}`);
    const e = new HttpError.InternalServerError();
    end({ labels: { success: false, status: e.status, type } });
    throw e;
}
fork icon2
star icon1
watch icon1

169
170
171
172
173
174
175
176
177
178
module.exports.UpgradeRequired = new HTTPErrors.UpgradeRequired()
module.exports.PreconditionRequired = new HTTPErrors.PreconditionRequired()
module.exports.TooManyRequests = new HTTPErrors.TooManyRequests()
module.exports.RequestHeaderFieldsTooLarge = new HTTPErrors.RequestHeaderFieldsTooLarge()
module.exports.UnavailableForLegalReasons = new HTTPErrors.UnavailableForLegalReasons()
module.exports.InternalServerError = new HTTPErrors.InternalServerError()
module.exports.NotImplemented = new HTTPErrors.NotImplemented()
module.exports.BadGateway = new HTTPErrors.BadGateway()
module.exports.ServiceUnavailable = new HTTPErrors.ServiceUnavailable()
module.exports.GatewayTimeout = new HTTPErrors.GatewayTimeout()
fork icon1
star icon0
watch icon7

+ 41 other calls in file

16
17
18
19
20
21
22
23
24
    });
    return res.status(200).json({ ok: true, room: new RoomDto(room) });
  } catch (error) {
    console.log(error);
    return next(
      httpErrors.InternalServerError('Error creating room. Try again.')
    );
  }
}
fork icon0
star icon1
watch icon1

122
123
124
125
126
127
128
129
130
131
if (!name.trim()) {
  throw createError.Conflict("You cannot set profile name as an empty");
} else {
  const user = await updateUserInfo(req.user._id, "name", name);
  if (!user) {
    throw createError.InternalServerError("Something sent wrong");
  } else {
    return res.status(200).json({ msg: "Name updated", user });
  }
}
fork icon0
star icon1
watch icon0

+ 15 other calls in file

80
81
82
83
84
85
86
87
88
89
const limit = req.query.limit || 10;
const type = req.query.type || "all";
try {
  const notes = await fetchAllNotes(page, limit, type);
  if (!notes) {
    throw createError.InternalServerError("something went wrong");
  } else {
    return res.status(200).json(notes);
  }
} catch (error) {
fork icon0
star icon1
watch icon0

+ 10 other calls in file

38
39
40
41
42
43
44
45
46
47

    /** save category in database */
    const category = await categoryModel.create({title, parent});

    /** return error if category creation wasn't successful */
    if (!category) throw createError.InternalServerError("ایجاد دسته بندی با مشکل مواجه شد لطفا مجددا تلاش نمایید");

    this.sendSuccessResponse(req, res, 201, "دسته بندی با موفقیت ایجاد شد", {category});
} catch (err) {
    next(err);
fork icon0
star icon0
watch icon1

+ 9 other calls in file

60
61
62
63
64
65
66
67
68
69
        productType,
        supplier: userId,
        features
    });
    /** return error if product was not saved */
    if (!createdProduct) throw createError.InternalServerError("ایجاد محصول با مشکل مواجه شد لطفا مجددا تلاش نمایید");
    /** return success message */
    return this.sendSuccessResponse(req, res, 201, undefined, {createdProduct});
} catch (err) {
    next(err);
fork icon0
star icon0
watch icon1

+ 9 other calls in file

12
13
14
15
16
17
18
19
20
21
try {
  await addCategorySchema.validateAsync(req.body);
  const { title, parent } = req.body;
  const category = await categoryModel.create({ title, parent });
  if (!category) {
    throw createErrors.InternalServerError(
      "creating category is not successfully"
    );
  }
  return res.status(httpStatus.CREATED).send({
fork icon0
star icon0
watch icon2

+ 14 other calls in file

79
80
81
82
83
84
85
86
87
88
try {
  const { id } = req.params;
  await this.findBlog({ _id: id });
  const result = await blogModel.deleteOne({ _id: id });
  if (result.deletedCount == 0)
    throw createError.InternalServerError("cant delete blog");
  return res.status(httpStatus.OK).json({
    data: {
      statusCode: httpStatus.OK,
      message: "blog already deleted",
fork icon0
star icon0
watch icon2

+ 9 other calls in file

131
132
133
134
135
136
137
138
139
140

    /** remove blog */
    const removedBlog = await blogModel.deleteOne({'_id': blogId});

    if (removedBlog.deleteCount <= 0)
        throw createError.InternalServerError("حذف پست با مشکل مواجه شد لطفا مجددا تلاش نمایید");

    this.sendSuccessResponse(req, res, 200, "پست با موفقیت حذف شد");
} catch (err) {
    next(err);
fork icon0
star icon0
watch icon1

11
12
13
14
15
16
17
18
19
20
try {
    await addCategorySchema.validateAsync(req.body);
    const { title, parent } = req.body;
    const category = await CategoryModel.create({ title, parent });
    if (!category)
        throw createHttpError.InternalServerError(
            "internall server error"
        );
    return res.status(httpStatus.CREATED).json({
        data: {
fork icon0
star icon0
watch icon1

+ 56 other calls in file

111
112
113
114
115
116
117
118
119
120
try {
    const { id } = req.params;
    await this.findBlog(id);
    const deleteResult = await BlogModel.deleteOne({ _id: id });
    if (deleteResult.deletedCount == 0)
        throw createHttpError.InternalServerError("can not delete");
    return res.status(httpStatus.OK).json({
        statusCode: httpStatus.OK,
        message: "blog deleted",
    });
fork icon0
star icon0
watch icon1

+ 37 other calls in file

119
120
121
122
123
124
125
126
127
128
const product = await this.findProduct(id);
const deleteResult = await ProductModel.deleteOne({
    _id: product._id,
});
if (deleteResult.deletedCount == 0)
    throw createHttpError.InternalServerError("delete failed");
return res.status(httpStatus.OK).json({
    statusCode: httpStatus.OK,
    message: "product delete successfully",
});
fork icon0
star icon0
watch icon1

+ 9 other calls in file