FINAL DECISION
try-and-error Google , , . Spring .
Spring Spring .
(REST) โโ .
, , , b ** lsh * t...
:
- a Spring Java
- Spring ( @ControllerAdvice ResponseEntityExceptionHandler)
- ( @Controller AbstractErrorController)
- POJO Jackson ()
( )
@Configuration
public class SpringConfig extends WebMvcConfigurerAdapter
{
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer)
{
configurer
.favorPathExtension(true).favorParameter(true)
.defaultContentType(MediaType.APPLICATION_XML)
.mediaType(...)
}
@Autowired
@SuppressWarnings ("SpringJavaAutowiringInspection")
public void setupDispatcherServlet(DispatcherServlet dispatcher)
{
dispatcher.setThrowExceptionIfNoHandlerFound(true);
}
@Bean
public ErrorProperties errorProperties()
{
ErrorProperties properties = new ErrorProperties();
properties.setIncludeStacktrace(ErrorProperties.IncludeStacktrace.NEVER);
properties.setPath("/error");
return properties;
}
}
Spring:
@ControllerAdvice(annotations = RestController.class)
public class WebExceptionHandler extends ResponseEntityExceptionHandler
{
@ExceptionHandler (Exception.class)
public ResponseEntity<Object> handleErrorResponse(Exception e)
{
logger.trace("Catching Exception in REST API.", e);
return handleExceptionInternal(e, null, null, null, null);
}
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex,
Object body,
HttpHeaders headers,
HttpStatus status,
WebRequest request)
{
logger.trace("Catching Spring Exception in REST API.");
logger.debug("Using " + getClass().getSimpleName() + " for exception handling.");
if(ex == null) throw new NullPointerException("empty exception");
String title = "API Error";
String msg = ex.getMessage();
if(status == null) status = HttpStatus.BAD_REQUEST;
WebErrorResponse response = new WebErrorResponse();
response.type = ex.getClass().getSimpleName();
response.title = title;
response.message = msg;
response.code = status.value();
if(headers == null) headers = new HttpHeaders();
try {
headers.setContentType(getContentType(request));
}
catch(NullPointerException e)
{
}
catch(IllegalArgumentException e)
{
return new ResponseEntity<>(status);
}
return new ResponseEntity<>(response, headers, status);
}
private static MediaType getContentType(WebRequest request) throws NullPointerException, IllegalArgumentException
{
String accepts = request.getHeader(HttpHeaders.ACCEPT);
if(accepts==null) throw new NullPointerException();
if(accepts.contains(MediaType.APPLICATION_XML_VALUE) ||
accepts.contains(MediaType.TEXT_XML_VALUE) ||
accepts.contains(MediaType.APPLICATION_XHTML_XML_VALUE))
return MediaType.APPLICATION_XML;
else if(accepts.contains(MediaType.APPLICATION_JSON_VALUE))
return MediaType.APPLICATION_JSON_UTF8;
else throw new IllegalArgumentException();
}
}
Spring Boot:
@Controller
@RequestMapping("/error")
public class CustomErrorController extends AbstractErrorController
{
protected final Logger logger = LoggerFactory.getLogger(getClass());
private final ErrorProperties properties;
@Autowired
public CustomErrorController(ErrorProperties properties, ErrorAttributes attributes)
{
super(attributes);
this.properties = new ErrorProperties();
}
@Override
public String getErrorPath()
{
return this.properties.getPath();
}
public ErrorProperties getErrorProperties()
{
return this.properties;
}
@RequestMapping (produces = {MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
public ResponseEntity<Object> handleError(HttpServletRequest request)
{
logger.trace("Catching Exception in REST API.");
logger.debug("Using {} for exception handling." , getClass().getSimpleName());
String endpoint = String.valueOf(request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI));
String code = String.valueOf(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE));
Exception ex = ((Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION));
if(ex == null) {
ex = new RuntimeException(String.valueOf(request.getAttribute(RequestDispatcher.ERROR_MESSAGE)));
}
if(ex instanceof NestedServletException && ex.getCause() instanceof Exception) {
ex = (Exception) ex.getCause();
}
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();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(getResponseType(request));
return new ResponseEntity<>(response, headers, getStatus(request));
}
private MediaType getResponseType(HttpServletRequest request)
{
String accepts = request.getHeader(HttpHeaders.ACCEPT);
if(accepts.contains(MediaType.APPLICATION_JSON_VALUE))
return MediaType.APPLICATION_JSON_UTF8;
else return MediaType.APPLICATION_XML;
}
}
, POJO WebErrorResponse int-.
REST API, XML JSON.
:
- ( ) Spring
- Spring Spring (, )
- 404 ( ) Spring
- mimetype (, /png, ) excelion Spring, w760 > (- mimetype).
, , .
,
Zipunrar