Issue
I have a nodejs server that uses the next() to catch errors. The issue I am running into is the thrown error is returning to the frontend in html. How can I change it to JSON.
A sample of my controller is:
function moveTable(req, res, next) {
const payload = jwtDecode(req.headers.authorization.split(' ')[1]);
authService.getAuthToken(payload.sub)
.then(token => cloverOrderService.moveTable(req.body, token.merchantId,token.cloverToken))
.then(data => res.send(data))
.catch(err => next(err));
}
My error handlrer function in my server.js is:
module.exports = errorHandler;
function errorHandler(err, req, res, next) {
res.setHeader('Content-Type', 'application/json');
console.log(JSON.stringify(err));
if (typeof (err) === 'string') {
// custom application error
return res.status(400).json({ message: err });
}
if (err.name === 'ValidationError') {
// mongoose validation error
return res.status(400).json({ message: err.message });
}
if (err.name === 'UnauthorizedError') {
// jwt authentication error
return res.status(401).json({ message: 'Invalid Token' });
}
// default to 500 server error
return res.status(500).json({ message: err.message });
}
My Angular error interceptor code is:
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
The error intercepted in the frontend is received in the following JSON format (Note: the error message is copied from debug so although it may not seem as JSON, the following is JSON):
{error
:
"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Error: Order Already Exists For Table general<br> at Object.moveTable (/Users/shahzibsarfraz/Documents/REPO/Dine-N-Go/clover-server-backend/cloverOrders/cloverOrders.service.js:843:15)<br> at process.processTicksAndRejections (node:internal/process/task_queues:95:5)</pre>\n</body>\n</html>\n"
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure response for http://localhost:4000/api/cloverOrders/moveTable: 500 Internal Server Error"
name
:
"HttpErrorResponse"
ok
:
false
status
:
500
statusText
:
"Internal Server Error"
url
:
"http://localhost:4000/api/cloverOrders/moveTable"}
as can be seen above, my error message that is thrown in the server is in the json error property of the returned error message but is in html format. How can i change it to be json?
I tried modifying the code in the errorHandler in node to add header of response type json but that had no effect. What am I missing?
Solution
So turns out my error handler wasn't being called. Moving the error handler after api calls in my server.js solved the issue.
Answered By - z123
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.