spring boot处理全局异常的时候,发现spring boot 不能处理404异常

我在spring boot处理全局异常的时候,发现spring boot 不能处理404异常如下:
/**
* 统一处理404异常
* @param e
* @return
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(value = {NoHandlerFoundException.class })
public ExceptionInfo<String> handleHttpRequestMethodNotFindException(HttpServletRequest req,NoHandlerFoundException e) {
ExceptionInfo<String> exceptionInfo = new ExceptionInfo<String>();
exceptionInfo.setMessage(e.getMessage());
exceptionInfo.setCode(404);
exceptionInfo.setUrl(req.getRequestURL().toString());
return exceptionInfo;
}
返回的还是系统默认的json
{
timestamp: 1503155310112,
status: 404,
error: Not Found,
message: No message available,
path: /qweqw/aa
}
 
已邀请:

wangkang - 80

赞同来自:

404有单独的处理方式,看一下BasicErrorController,然后spring boot跟我们留了口子的,可以用自己的实现替换原有的实现

参照BasicErrorController实现一个自己的errorController,
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ExceptionController extends AbstractErrorController {
.........
}
然后在进行配置:
/**
* ErrorControllerConfig
*/
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(ResourceProperties.class)
public class ExceptionControllerConfig {
/**
* errorViewResolvers
*/
@Autowired(required = false)
private List<ErrorViewResolver> errorViewResolvers;

/**
* serverProperties
*/
private final ServerProperties serverProperties;

/**
* 构造函数
*
* @param serverProperties serverProperties
*/
public ExceptionControllerConfig(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
}

/**
* exceptionController
*
* @param errorAttributes errorAttributes
* @return ExceptionController
*/
@bean
public ExceptionController exceptionController(ErrorAttributes errorAttributes) {
return new ExceptionController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers);
}


}

要回复问题请先登录注册