Skip to content

Instantly share code, notes, and snippets.

@An0nymous0
Created April 24, 2019 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save An0nymous0/d28e9b8dd547967294d8e2635a39b5fb to your computer and use it in GitHub Desktop.
Save An0nymous0/d28e9b8dd547967294d8e2635a39b5fb to your computer and use it in GitHub Desktop.
[Spring RestFul GlobalExceptionHandler] Spring全局异常处理 #java #spring #common
package com.demo.servicemesh1.config;
import com.demo.servicemesh1.common.ResponseMessage;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
@Log4j2
/**
* https://stackoverflow.com/questions/12806386/standard-json-api-response-format
*/
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseMessage defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
log.error(e.getMessage(), e);
if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
return ResponseMessage.error(HttpStatus.NOT_FOUND.value(), e.getMessage());
} else {
return ResponseMessage.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment