Back in the day, I used to retrieve HTTP responses with a TypeScript object.
validateTokenHttp(token: string): Observable<User> {
return this.http.get<User>(`${environment.api}/auth/verifyToken/${token}`);
}
Sometimes it would return a User
object, or an Account Not Verified
message, or an Account Not Valid
response, or something else entirely.
The big question is, what is the best approach to handle these various responses?
Here are some possibilities I've been considering:
Send the response with a status code of
401
or another,this.validateTokenHttp(token) .subscribe( (user) => { // perform successful operation }, (error) => { if(error.status == 401){ console.log(error.error); // handle the exception } } );
- Response
// Status Code: 401 {message: "Account Not Verified"}
NOTE: In this scenario, we are referring to the status code
401
, but there could be multiple validation scenarios on the server that don't align with401
.- Response
Include validation errors within the HTTP response with a status code of
200
validateTokenHttp(token: string): Observable<any> { return this.http.get<any>(`${environment.api}/auth/verifyToken/${token}`); } getUser(){ this.validateTokenHttp(token) .subscribe(data=>{ if(data.success == true){ //perform successful operation } else{ //handle the exception } }); }
Response 1
//Status Code: 200 {success: true, data: "--User details JSON object"}
Response 2
//Status Code: 200 {success: false, message: "Account Not Verified"}
If we opt for solution 2, we would need to change the return type from
validateTokenHttp(token: string): Observable<User>
to validateTokenHttp(token: string): Observable<any>
. However, using the <any>
type might not be the ideal choice.
Is there a way to expect two possible objects?
Observable<User || CustomErrorObject>
How can we ensure that we receive a User
object?
Can someone please advise on the best practice for handling these types of server validations and responses?