I am sending an unauthorized status code (401) with a message if the user is not logged in spring boot application, the process works fine if we test it with the postman, however, it does not work with angular.
For example:
there is an API
http://localhost:8080/api/alarms?page=0&size=20
Postman:
{
"timestamp": "2022-05-08T09:40:52.454 00:00",
"status": 401,
"error": "Unauthorized",
"path": "/api/alarms"
}
Angular:
if we call the same API from the angular application, it gives the error but the error message and status codes are not the same
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"headers": {}
},
"status": 0,
"statusText": "Unknown Error",
"url": "http://localhost:8080/api/alarms?page=0&size=20",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for http://localhost:8080/api/alarms?page=0&size=20: 0 Unknown Error",
"error": {
"isTrusted": true
}
}
Server-side code:
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unauthorized");
}
How to catch the status code and message specified on the sever-side in the angular application?
CodePudding user response:
To catch the status code and message specified on the sever-side in the angular application, you can handle this using HTTP Interceptor in your angular application to handle all the global errors in your application.
Please refer to the below links
Http interceptor for global error handling
Another link for global error handling
CodePudding user response:
Problem solved:
The problem was actually CORS problem, to solve the issue u can refer to this answer.