const HttpError = require("../models/http-error");
//http-error.js
class HttpError extends Error {
constructor(message, errorCode) {
super(message); // Add a "message" property
this.code = errorCode; // Adds a "code" property
}
}
module.exports = HttpError;
What is the differences betwen err and error what is the job over here err?
err is An optional identifier to hold an exception object for the associated catch-block. MDN try...cactch
const error is the object of your custom error handler
Related
If I use Throw new Error("User not found"), then it gives in response
{status:false,message:"User Not Found"}
But with status code 500, And I need Status 400 in Postman
custom Error using throw function
but if we use res.status(500).send({ status: false, message: "User not found" })
then it gives status code 400, And I need Status 400 in Postman . So, I need same status code in postman only.This is the problem. Tyler2P and Abin Bala , I followed your code but I am unable to get desired status code in postman status.
You can create a custom error class as below and throw it with appropriate message and httpCode. You can also add more properties. Then you can catch the custom error object using the catch block and get the required values.
class CustomError extends Error {
name;
httpCode;
message;
constructor(name,httpCode, message){
super(message);
this.name = name;
this.httpCode = httpCode;
this.message = message;
}
}
errorThrowingFunction.js:
//import the custom error class in the module that you //are going to use it.
errorThrowingFunction = () => {
const authToken = myCache.get("token");
if (!authToken) {
throw new CustomError('Error',401,'token missing');
} else {
return authToken;
}
}
index.js:
handler = () => {
try {
errorThrowingFunction();
} catch(error){
const response = {
statusCode: error.httpCode,
body: JSON.Stringify(error.message),
isBase64Encoded: false,
//add other headers
}
return response;
//if you are using this in rest service, the use below line
//return res.status(error.httpCode)send(response);
}
}
I am very new to typescrypt, and I'm currently in the process of migrating a project from JS to TS.
While I was changing some things on my server endpoints, an error appeared:
Property 'email' does not exist on type 'string | JwtPayload'
This is my code so far:
try {
const token = await TokenController.getTokenFromRequest(req);
const decoded = jwt.decode(token);
const user = await AuthController.getUserByMail(decoded.username); // <- Error appears here
res.json(user);
} catch (error: any) {
ErrorController.errorCallback(error, res);
}
Edit: My code for 'getUserByMail' looks like so:
static async getUserByMail(email: string, includePassword = false) {
let query = User.findOne({
email: email
});
if (!includePassword) {
query.select('-password');
}
return query.exec();
}
I know that the error happens because I'm trying to access a property that string doesn't have. Any suggestions?
Create global.d.ts:
// global.d.ts
declare module "jsonwebtoken" {
export interface JwtPayload {
//make optional so when you try to decode stuff other than user it will show it can be undefined
email?: string;
}
}
Following code generates exception as UserAlreadyExist.
Optional<User> userCheck = userRepository.findByUsername(createRequest.getUsername());
if(StringUtils.hasText(userCheck.get().getUsername())){
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
}
When i try to get error message from my react app with these codes i only get Internal server error message. My header contains header token and application/JSON header.
export const createUserService = (data) => {
return new Promise(((resolve, reject) => {
axios.post(USERS_BASE, data, getHeaderWithToken())
.then(function (response) {
resolve(response);
})
.catch(error=>{
console.log(error)//returns "Internal Server Error" message
console.log(error.response) // returns object with empty message field and other parameters.
reject(error)
})
}));
};
How can i get the error message i sent like
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
this is my UserAlreadyExistException class btw.
public class UserAlreadyExistException extends RuntimeException {
public UserAlreadyExistException(String message) {
super(message);
}}
You can return custom Response with #RestControllerAdvice for the custom exception you are throwing.
Please check the example below.
#RestControllerAdvice
public class ControllerExceptionHandler {
#ExceptionHandler(value = {UserAlreadyExistException.class})
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ErrorMessage userAlreadyExistException(UserAlreadyExistException ex, WebRequest request) {
ErrorMessage message = new ErrorMessage(
status,
date,
ex.getMessage(),
description);
return message;
}
}
It will be much easier for you to see the error in your Frontent application with a Response that you will return like this.
I'm trying to throw an exception in Node.js with an object. But I don't know how to customize the return class.
Example:
class BusinessError extends Error {
constructor(code, status, message) {
super(message);
this.code = code;
this.name = 'Error';
this.status = status;
}
}
const error = {
code: '001',
status: 500,
message: 'Error',
}
throw new BusinessError(error.code, error.status, error.message);
But, the other attributes do not appear in the return.
Ex:
{
"message": "TypeError: foo is not a function"
}
But, i wanted it to be like this
{
"message": "TypeError: foo is not a function",
"code": 'X-100',
"status": 500
}
Your constructor doesn't accept an object but you instantiated BusinessError with an object. You could try destructuring the object in the class constructor like so
class BusinessError extends Error {
constructor({ code, status, message }) {
super(message);
this.name = 'BusinessError';
this.status = status;
}
}
const error = {
code: '001',
status: 500,
message: 'This is an Error',
}
throw new BusinessError(error);
I would like to keep all of error descriptions in a single .js file as a dictionary, so that I can display the appropriate description from the rest of my JavaScript web app. I am very new to JS web app development and I am wondering how to achieve this.
currently I have been trying this:
errorDesc.js:
var descriptions = {
errorCode00 : "description",
errorCode02 : "description",
errorCode03 : "description"
}
export function getResponseDescription(name) {
return descriptions[name];
}
main.js:
import {getResponseDescription} from "./errorDesc";
But in the console I get the following error:
Uncaught SyntaxError: Unexpected token {
I will suggest you have a file consist of error classes (used to set an error message and error name) which extend Error class and in the constructor assign the error message and error name to the object e.g.
class AuthorizationError extends Error {
constructor(message) {
super(message);
this.name = 'AuthorizationError';
this.message = message;
}
}
// classes of other error types
after that set, the status code based on the type of error and return e.g.
const errorHandler = (error, req, res, next) => {
const message = error.message || 'Something went wrong';
let status = null;
switch(error.name) {
case 'AuthorizationError':
status = 403;
break;
// other error types
}
res.status(status).json({ message });
}
wherever you encounter error create a new instance of the type of error class
next(new AuthorizationError('Username or password do not match'));