推荐直接使用@ResponseStatus注解,文章最后有示例!
NoHandlerFoundException异常处理方法返回ResponseEntity对象,并设置status为HttpStatus.NOT_FOUND即可:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.yilabao.domain.ReturnVO;
/**
* 全局异常处理
*
* @author yilabao
* @date 2021年1月23日
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 404异常处理<br>
* 返回ResponseEntity,保留网络请求404状态码
*
* @author yilabao
* @date 2021年1月23日
* @param e
* @return ResponseEntity<ReturnVO<String>>
*/
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<ReturnVO<String>> noHandleFoundException(NoHandlerFoundException e) {
String message = e.getMessage();
LOG.error(message, e);
ReturnVO<String> errorBody = new ReturnVO<String>().error(message);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorBody);
}
/**
* Exception异常处理
*
* @author yilabao
* @date 2021年1月23日
* @param e
* @return ReturnVO<String>
*/
@ExceptionHandler(Exception.class)
public ReturnVO<String> handleException(Exception e) {
String message = e.getMessage();
LOG.error(message, e);
return new ReturnVO<String>().error(message);
}
}
还试了一种方式,继承ResponseEntityExceptionHandler类,重写handleNoHandlerFoundException和handleExceptionInternalCustom方法,自定义404响应信息。
如果用第2种方式,第1种方式里面就不能处理NoHandlerFoundException和Exception,否则优先执行第1种。
注意添加配置参数:
spring:
mvc:
throw-exception-if-no-handler-found: true
resources:
add-mappings: false
20220127
直接使用@ResponseStatus注解!
20220318
@org.springframework.web.bind.annotation.ResponseStatus(org.springframework.http.HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public AjaxResult handlerNoFoundException(NoHandlerFoundException e) {
LOG.error(e.getMessage(), e);
AjaxResult errorBody = AjaxResult.error(HttpStatus.NOT_FOUND, "路径不存在,请检查路径是否正确");
return errorBody;
}