package com.yl.controlleradvice.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/** * 测试出现异常后是否跳转到对应的thymeleaf模板 */
@Controller
public class TestController2 {
@GetMapping("/test")
public void test() {
int a = 1 /0;
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>error message</h1>
<div th:text="${error}"></div>
</body>
</html>
package com.yl.controlleradvice.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
//@RestControllerAdvice
@ControllerAdvice
public class TestController {
@ExceptionHandler(Exception.class)
public ModelAndView CustomException(Exception e) {
ModelAndView modelAndView = new ModelAndView("01");
modelAndView.addObject("error",e.getMessage());
return modelAndView;
}
}
package com.yl.controlleradvice.model;
public class Book {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
package com.yl.controlleradvice.model;
public class Author {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@ControllerAdvice主要用于返回视图
@RestControllerAdvice主要用于直接返回错误信息
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_41359273/article/details/120406555
内容来源于网络,如有侵权,请联系作者删除!