((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
返回当前的HttpServletRequest
package bj
import org.omg.CORBA.Object
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.ApplicationListener
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.HandlerExceptionResolver
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@SpringBootApplication
@RestController
class App : ApplicationListener<ApplicationReadyEvent>, WebMvcConfigurer {
override fun onApplicationEvent(event: ApplicationReadyEvent?) {
println("here")
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(App::class.java, *args)
}
}
@RequestMapping("/")
fun home(): Object {
throw StackOverflowError("Over")
}
@RequestMapping("/err")
fun err(): Object {
throw IndexOutOfBoundsException("Index")
}
override fun extendHandlerExceptionResolvers(resolvers: MutableList<HandlerExceptionResolver>) {
super.extendHandlerExceptionResolvers(resolvers)
resolvers.add(HandlerExceptionResolver { request, response, handler, ex ->
println("Exception: $ex")
return@HandlerExceptionResolver null
})
}
}
@ControllerAdvice
@RestController
class MyAdv {
@ExceptionHandler(IndexOutOfBoundsException::class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun processException(e: Exception): Any {
return e.localizedMessage;
}
}
org.springframework.web.bind.annotation.RestController#value
表示的是 bean 的名字,不是 URL ,配置 URL 要用注解 @RequestMapping
Spring默认404不抛异常,所以需要强制抛出异常,然后用@ExceptionHandler(NoHandlerFoundException::class)
处理
以下两条属性的设置缺一不可:
spring.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true