cors issue when throwing a runtime exception with spring and docker cors issue when throwing a runtime exception with spring and docker docker docker

cors issue when throwing a runtime exception with spring and docker


What I finaly ended up to do was adding an handler to the exception in the controller that return me the right message : this way :

@ExceptionHandler({ EmailAlreadyExistException.class })public String handleException() {    return "{\"error\": \"" + messages.getMessage("emailAlreadyExist", null, Locale.ENGLISH) + "\"}";}


Did you try to proxy the API calls? In the angular project, you can create a proxy.conf.json file and add below configurations.

{  "/api": {    "target": "http://localhost:3000",    "secure": false  }}

Then in the package.json change the start,

"start": "ng serve --proxy-config proxy.conf.json"

If you want to do it from the psring side add @CrossOrigin to controller.

But if you think you are going to face the same issue in production, my advice is to use a reverse proxy like Nginx. You're Angular application and APIs are served via the same port but all the APIs are prefixed with api. From the Nginx side, you can filter API calls using api prefix and proxy them to backend service.


Spring boot uses a default error controller. You can supply your own and add an Access-Control-Allow-Credentials header to the response:

import org.springframework.boot.web.servlet.error.ErrorController;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.RequestDispatcher;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@RestControllerpublic class CustomErrorController implements ErrorController {    @RequestMapping("/error")    public String handleErrors(HttpServletRequest request, HttpServletResponse response) {        response.addHeader("Access-Control-Allow-Credentials","true");        String errorMessage = request.getAttribute(RequestDispatcher.ERROR_MESSAGE).toString();        return errorMessage;    }    @Override    public String getErrorPath() {        return "/error";    }}