设置spring boot 默认返回的错误
使用kotlin 书写返回的错误json格式
fun get404(): String {
return """{"code":"404","message":"Not found"}""".trimIndent()
}
设置全局异常
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handlerException(Exception e) {
if (e instanceof NoHandlerFoundException) {
return ResultStringKt.get404();
} else {
e.printStackTrace();
return ResultStringKt.get404();
}
}
}
设置properties
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=false