public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
}
@Configuration
public class SpringConfig extends WebMvcConfigurerAdapter
{
// ... init stuff if needed
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer)
{
// setup content negotiation (automatic detection of content types)
configurer
// use format parameter and extension to detect mimetype
.favorPathExtension(true).favorParameter(true)
// set default mimetype
.defaultContentType(MediaType.APPLICATION_XML)
.mediaType(...)
// and so on ....
}
/**
* Configuration of the {@link DispatcherServlet} bean.
*
*
This is needed because Spring and Spring Boot auto-configuration override each other.
*
* @see
* Stackoverflow - Spring Boot REST service exception handling
*
* @param dispatcher dispatcher servlet instance
*/
@Autowired
@SuppressWarnings ("SpringJavaAutowiringInspection")
public void setupDispatcherServlet(DispatcherServlet dispatcher)
{
// FIX: for global REST error handling
// enable exceptions if endpoint not found (instead of static error page)
dispatcher.setThrowExceptionIfNoHandlerFound(true);
}
/**
* Creates the error properties used to setup the global REST error controller.
*
*
Using {@link ErrorProperties} is compliant to base implementation if Spring Boot's
* {@link org.springframework.boot.autoconfigure.web.BasicErrorController}.
@ControllerAdvice(annotations = RestController.class)
public class WebExceptionHandler extends ResponseEntityExceptionHandler
{
/**
* This function handles the exceptions.
*
* @param e the thrown exception
*
* @return error message as XML-document
*/
@ExceptionHandler (Exception.class)
public ResponseEntity
Spring Boot的错误控制器:
@Controller
@RequestMapping("/error")
public class CustomErrorController extends AbstractErrorController
{
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* The global settings for this error controller.
*/
private final ErrorProperties properties;
/**
* Bean constructor.
*
* @param properties global properties
* @param attributes default error attributes
*/
@Autowired
public CustomErrorController(ErrorProperties properties, ErrorAttributes attributes)
{
super(attributes);
this.properties = new ErrorProperties();
}
@Override
public String getErrorPath()
{
return this.properties.getPath();
}
/**
* Returns the configuration properties of this controller.
*
* @return error properties
*/
public ErrorProperties getErrorProperties()
{
return this.properties;
}
/**
* This function handles runtime and application errors.
*
* @param request the incorrect request instance
*
* @return error message as XML-document
*/
@RequestMapping (produces = {MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
public ResponseEntity handleError(HttpServletRequest request)
{
logger.trace("Catching Exception in REST API.");
logger.debug("Using {} for exception handling." , getClass().getSimpleName());
// original requested REST endpoint
String endpoint = String.valueOf(request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI));
// status code
String code = String.valueOf(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE));
// thrown exception
Exception ex = ((Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION));
if(ex == null) {
ex = new RuntimeException(String.valueOf(request.getAttribute(RequestDispatcher.ERROR_MESSAGE)));
}
// release nested exceptions (we want source exception only)
if(ex instanceof NestedServletException && ex.getCause() instanceof Exception) {
ex = (Exception) ex.getCause();
}
// build response body
WebErrorResponse response = new WebErrorResponse();
response.title = "Internal Server Error";
response.type = ex.getClass().getSimpleName();
response.code = Integer.valueOf(code);
response.message = request.getMethod() + ": " + endpoint+"; "+ex.getMessage();
// build response headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(getResponseType(request));
// build the response
return new ResponseEntity<>(response, headers, getStatus(request));
}
/*@RequestMapping (produces = {MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE})
public ResponseEntity