Stacktrace exceptions in Spring rest answers

I have several Rest web services implemented through Spring. The problem is that if any exception is thrown the webservice returns a json object with a formatted error message containing the stacktrace. Can I have one exception handling point and return my custom json objects with messages that don't contain a stacktrace?

I see descriptions for spring mvc but im not really using that to build my views etc.

+3


source to share


2 answers


Spring provides a turnkey solution to handle all of your custom exceptions from one point. You need an annotation @ControllerAdvice

in your exception controller:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String exception(Exception e) {

        return "error";
    }
}

      



If you want to dive deeper into Springs @ExceptionHandler

at the individual controller level or @ControllerAdvice

at the global application level here is a good blog.

+2


source


To handle exceptions thrown from a spring application at one point, this is the best way to do it. @ControllerAdvice will create an aspect join point that will catch all exceptions with the required match types bound to the appropriate public method. Here, public ResponseEntity handleDataIntegrityViolationException (DataIntegrityViolationException dataIntegrityViolationException, WebRequest) handles DataIntegrityViolationException thrown from the system in one place.



@ControllerAdvice
public class GlobalControllerExceptionHandler {
private Logger logger = Logger.getLogger(this.getClass());
private HttpHeaders header = new HttpHeaders();

@Autowired
private MessageSource messageSource;

public GlobalControllerExceptionHandler() {
    header.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
}

/**
 * @param dataIntegrityViolationException
 * @param request
 * @return
 */
@ExceptionHandler({ DataIntegrityViolationException.class })
public ResponseEntity<?> handleDataIntegrityViolationException(DataIntegrityViolationException dataIntegrityViolationException,
        WebRequest request) {

    String message = ExceptionUtils.getMessage(dataIntegrityViolationException);
    logger.error("*********BEGIN**************DataIntegrityViolationException******************BEGIN*******************\n");
    logger.error(message, dataIntegrityViolationException.fillInStackTrace());
    logger.error("*********ENDS**************DataIntegrityViolationException*******************ENDS*****************************\n");
    return ResponseEntity.status(HttpStatus.CONFLICT).headers(header).body(dataIntegrityViolationException);
}

}

      

0


source







All Articles