How to get specific error instead of Internal Server Error?

笑着哭i 提交于 2019-12-01 08:49:10

问题


I am getting Internal Server Error on postman even though I am throwing a custom exception from my code exception. I want to see the exception of having a valid error message and error code, what I am throwing. It will be a great help if anyone of you can help me on this point. Like how I can get a better error message. Adding below code snap. Thanks in advance.

@Service
public class FetchActionImpl implements FetchAction {

    private static Logger log = LoggerFactory.getLogger(FetchActionImpl.class);

    @Autowired
    FetchActionServiceImpl fetchActionService;// = new FetchActionServiceImpl();

    @Override
    public FetchResponse fetchActionRequest(String caseId) throws BBWException,Exception{
        //String resp ="";
        log.info("fetchaction Request: {}",ApplicationConstants.LOG_ENTRY_MESSAGE);
        log.info("The caseId received from BRASS:\n {}",caseId);
        FetchResponse resp = null;
        try{
            if(true) {
                throw new BBWException("500","Test");
                }
            resp = fetchActionService.fetchIt(caseId);

            log.debug("fetchaction Response: {}",resp.toString());

        } 
        catch (BBWException be) {
            throw be;
        }
        catch (Exception e) {
            throw new BBWException("500",e.getMessage());
        }
        return resp;
        }

}


@Api
@Path("/fetch_service")
public interface FetchAction {

    @GET
    @Path("/fetchaction/caseid/{caseid}")
    @Produces({MediaType.APPLICATION_JSON})
    //@Consumes({MediaType.TEXT_XML})
    @ApiOperation(
            value = "Respond BRASS Request",
            notes = "Returns a XML object "                 
    )
    @ApiResponses(
            value = {
                    @ApiResponse(code = 404, message = "Service not available"),
                    @ApiResponse(code = 500, message = "Unexpected Runtime error")
                    })
    public FetchResponse fetchActionRequest(@PathParam("caseid") String caseid) throws BBWException, Exception;

}`

    public class BBWException extends Exception {

            private static final long serialVersionUID = -7987978270260338068L;

            private String errorCode;
            private String errorMessage;

            public BBWException(String errorCode, String errorMessage) {
                super(errorMessage);
                this.errorCode = errorCode;
                this.errorMessage = errorMessage;
            }

            public String getErrorCode() {
                return errorCode;
            }


            public void setErrorCode(String errorCode) {
                this.errorCode = errorCode;
            }


            public String getErrorMessage() {
                return errorMessage;
            }
        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }

        @Override
        public String toString() {

            return (this.errorCode + " " + this.errorMessage);
        }
}

回答1:


Each time the (uncaught) exception is throw, SpringBoot returns Http-500 Internal Server Error. There are many ways of handling exceptions in Spring.

Let's say I have my controller and I implicitly throw an exception.

@RestController
public class HelloWorldController {

    @GetMapping("/hello-world")
    public String helloWorld() {
        throw new MyCustomException("I just can't say hello!");
    }
}

It's the same as yours - you can specify anything in the exception.

First:

One of the way of handling it, is to create a class with @ControllerAdvice annotation.

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MyCustomException.class)
    public ResponseEntity<String> handlyMyCustomException(MyCustomException e) {
        logger.error("error occurred {}", e);
        return new ResponseEntity<>("Something happened: " + e.getMessage(), HttpStatus.I_AM_A_TEAPOT);
    }
}

This way you are able to catch the exception of your choice (globally) and return the message with the HTTP Response Status of your choice, not neccessarily I_AM_A_TEAPOT

Second:

    @ExceptionHandler(MyCustomException.class)
        public ResponseEntity<String> handlyMyCustomException(MyCustomException e) {
            logger.error("error occurred {}", e);
            return new ResponseEntity<>("Something happened: " + e.getMessage(), HttpStatus.I_AM_A_TEAPOT);
        }

You could also create only method annotated with @ExceptionHandler in your controller class - but this is not global and is going to work only for this exact controller calls.

Result below:

Third:

Another way of dealing with exceptions is to create your own error .html files. If you place a file in resources/static/error/500.html it should be returned when the Http-500 Internal Server Error is thrown.



来源:https://stackoverflow.com/questions/54328633/how-to-get-specific-error-instead-of-internal-server-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!