My Spring Boot Controller throws an Exception, but on the JS Fetch side, the flow does not go into catch(err)
. Rather, it goes into the then()
as below, which is incorrect.
@PostMapping(path = "/submit")
public void submit(@RequestBody CaseInquiry caseInquiry) throws Exception {
// test
throw new Exception("test");
}
JS Fetch:
const submit = () => {
fetch("/app/submit", {
method: "POST",
body: JSON.stringify(Object.fromEntries(valueMap)),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.text())
.then(result => {
alert('Success'); // Comes here (incorrectly with JSON string)
}).catch(error => {
alert('Error: ' + error); // Does not come here
});
}
}
The then()
result is
'{"timestamp":"2023-08-21T13:07:06.832+00:00","status":500,"error":"Internal Server Error","path":"/app/submit"}'
I found in this thread that this JSON output comes from Spring Boot's BasicErrorController
.
It's used as a fallback when your application hasn't handled an exception using Spring MVC (with an ExceptionHandler or ControllerAdvice, for example) or a container error page.
So is there a way for me in Spring Boot to allow exceptions to propagate so that I catch them with catch()
in the JS Fetch?