Created
April 24, 2019 08:49
-
-
Save An0nymous0/d28e9b8dd547967294d8e2635a39b5fb to your computer and use it in GitHub Desktop.
[Spring RestFul GlobalExceptionHandler] Spring全局异常处理 #java #spring #common
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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