您好,登錄后才能下訂單哦!
怎么在SpringBoot中通過(guò)干掉Whitelabel Error Page返回自定義內(nèi)容?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
SpringBoot中對(duì)于錯(cuò)誤請(qǐng)求的頁(yè)面是長(zhǎng)這樣的,
然而我們?cè)谠L問(wèn)在一些網(wǎng)站時(shí),如果請(qǐng)求錯(cuò)誤,一般都會(huì)有友好美觀的提示,比如知乎這個(gè),這比起一堆錯(cuò)誤信息要友好的多了。
我們可以根據(jù)項(xiàng)目業(yè)務(wù)來(lái)自定義錯(cuò)誤請(qǐng)求(RequestMapping中沒(méi)有映射到的請(qǐng)求)的處理,比如返回自定義錯(cuò)誤頁(yè)面或者Json字符串。
我們看看SpringBoot中對(duì)于錯(cuò)誤請(qǐng)求是如何處理的。SpringBoot項(xiàng)目中搜索Whitelabel
定位到類WhitelabelErrorViewConfiguration
,可以看到它是ErrorMvcAutoConfiguration
的一個(gè)靜態(tài)內(nèi)部類,而且正是這個(gè)類處理的錯(cuò)誤請(qǐng)求的,代碼中的defaultErrorView
正是我們看到的默認(rèn)錯(cuò)誤頁(yè)面。
@Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true) @Conditional(ErrorMvcAutoConfiguration.ErrorTemplateMissingCondition.class) protected static class WhitelabelErrorViewConfiguration { private final ErrorMvcAutoConfiguration.StaticView defaultErrorView = new ErrorMvcAutoConfiguration.StaticView(); @Bean(name = "error") @ConditionalOnMissingBean(name = "error") public View defaultErrorView() { return this.defaultErrorView; } // and so on... }
仔細(xì)研究這個(gè)代碼,我們不難發(fā)現(xiàn),我們至少有兩種方法可以替換掉默認(rèn)的實(shí)現(xiàn)自定義錯(cuò)誤頁(yè)面。
入手點(diǎn)1:
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
入手點(diǎn)2:
@Bean(name = "error") @ConditionalOnMissingBean(name = "error")
3. 嘗試
3.1 嘗試 1
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
我們看到server.error.whitelabel.enabled
控制了這個(gè)類是否裝配,我們可以在配置中將其設(shè)為false
server: error: whitelabel: enabled: false path: /error
該配置類為ErrorProperties
,默認(rèn)的錯(cuò)誤請(qǐng)求為/error
,將 whitelabel 禁用后在 controller 中定義請(qǐng)求 /error
返回自定義內(nèi)容。
@Controller public class ErrorController { @RequestMapping("/error") @ResponseBody public R error(HttpServletRequest request) { Integer status = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if (Objects.nonNull(status)) { HttpStatus httpStatus = HttpStatus.valueOf(status); return RUtils.fail(httpStatus); } return RUtils.fail("Error"); } }
運(yùn)行!一頓操作猛如虎,仔細(xì)一看原地杵,想法不錯(cuò),但瘋狂報(bào)錯(cuò):
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/D:/Environment/Maven/repository/io/springfox/springfox-spring-web/2.9.2/springfox-spring-web-2.9.2.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/D:/Environment/Maven/repository/io/springfox/springfox-spring-web/2.9.2/springfox-spring-web-2.9.2.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [xxx/xxx/xxx/config/WebMvcConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'basicErrorController' method
org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
to { /error}: There is already 'errorController' bean method
具體報(bào)錯(cuò)原因未作分析,懷疑是我項(xiàng)目設(shè)置有問(wèn)題,筆者使用的SpringBoot版本是2.3.6.RELEASE,大家可以嘗試一些行不行。既然第一個(gè)方法嘗試接著嘗試失敗,那就試試第二個(gè)吧。
3.2 嘗試2
@Bean(name = "error") @ConditionalOnMissingBean(name = "error")
這個(gè)操作更簡(jiǎn)單,我們只要向IoC
容器中注入一個(gè)名為error
的Bean
即可,返回類型為View
:
@Configuration public class MyConfig { @Bean("error") public View error() { ModelAndView view = new ModelAndView(new MappingJackson2JsonView()); return view.getView(); } }
其中new MappingJackson2JsonView()
返回的Json字符串的 View ,當(dāng)然你也可以根據(jù)業(yè)務(wù)需求靈活使用,如果想獲取HttpServletRequest
可以這樣獲取,但使用時(shí)需要注意判空,因?yàn)锽ean實(shí)例化注入是可能獲取不到HttpServletRequest
而造成NPE
,項(xiàng)目啟動(dòng)失敗。
public static HttpServletRequest getRequest() { return Optional.ofNullable(RequestContextHolder.getRequestAttributes()) .map(r -> ((ServletRequestAttributes) r).getRequest()) .orElse(null); }
結(jié)果當(dāng)然是沒(méi)問(wèn)題的,會(huì)返回以下信息:
看完上述內(nèi)容,你們掌握怎么在SpringBoot中通過(guò)干掉Whitelabel Error Page返回自定義內(nèi)容的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。