Issue
I am not able to see the message (in React.js catch block) set while throwing Exception (by server in Java).
Situation: User wants to perform some action (via myService), some verification w.r.t action can be done only on back-end, if that fails how to show the user what was the reason of failure?
Service (Java):
@GetMapping(path = {/*Servive_path*/}, produces = APPLICATION_JSON_VALUE)
public MyClass myService(@RequestParam String param) {
throw new RuntimeException("This is error message");
}
Action (React.js):
const myServive = (param) => {
return async (dispatch, getState) => {
return request({
url: ENDPOINTS.MY_SERVICE,
method: methods.GET,
params: { param }
})
.then(res => {
dispatch(saveResult(res));
dispatch(
notify({
title: "Successful",
message: "It was successfully.",
status: 200,
dismissAfter: CONFIG.NOTIFICATION_TIMEOUT
})
);
})
.catch(err => {
console.log("err.data: ", err.data); //Output-> err.data:
console.log("err.message: ", err.message); //Output-> err.message: undefined
dispatch(
notify({
title: "Some error occured",
message: **//Want to set the error message**,
status: "error",
dismissAfter: CONFIG.NOTIFICATION_TIMEOUT
})
);
});
};
};
Want to show the exception message by setting value in massage in catch block of action.
Output
err.data: ""
err.message: undefined
Also,
err.status: 500
err.request.response: ""
err.request.responseText: ""
err.request.responseType: ""
err.request.status: 500
err.request.statusText: ""
Please help.
Solution
By default in case of exception Spring return http status 500 with Content-Type: text/html;charset=UTF-8 and generates html page with error description. Your error description will be in the last line of this page after
<div>There was an unexpected error (type=Internal Server Error, status=500).</div>
and will look like
<div>This is error message</div>
Of course you can write crutch in your code and parse this page using React, but I wouldn't recommend so. It's much better to add Controller advice and write custom exception handling. In your case something like this
import lombok.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ExceptionRestResponse handleCustomException(Exception exception) {
return new ExceptionRestResponse(500, exception.getMessage());
}
@Value
public static class ExceptionRestResponse {
int code;
String message;
}
}
Then you will get response with Content-Type: application/json which will look like
{
"code": 500,
"message": "This is error message"
}
Answered By - Bohdan Petrenko
Answer Checked By - David Goodson (JavaFixing Volunteer)